Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

Can anyone help me on how to write the query for the below.

I have a table Test where records are like...

Number Email Type
100 abc@t.com P
100 aaa@as.com S
101 qws@sd.com P
102 rtt@y.com P


I need the result like below.

Number Email Type
100 abc@t.com P
101 qws@sd.com P
102 rtt@y.com P


Means, No duplicates records should exist. So here for 100, I have type P and S. I need to just display P record with the corresponding Email.

Can Anyone help on this.

Thanks.
Posted

For SQL2005

SQL
select  a.Number,
        b.Email,
        b.Type
from    (
        select  distinct
                Number
        from    Test
        ) as a
cross
apply   (
        select  top 1
                Email,
                Type
        from    Test
        where   Number = a.Number
        order
        by      case
                    when Type = 'P' then 1
                    when Type = 'S' then 2
                    when Type = 'I' then 3
                    else 10
                end
        ) as b
 
Share this answer
 
Comments
CGN007 24-Feb-12 7:03am    
grt...!!!5+
Your requirements are not completely clear - for example, are 'P' and 'S' the only "types" there might be? Is it safe to take the alphabetical first "type"?

If so, this works:

SQL
select * from test2
 inner join (select number,  min(type) as type
             from test2
             group by number) as v1
             on test2.number = v1.number
             and test2.type = v1.type

Scott
 
Share this answer
 
Comments
vasini 22-Feb-12 13:56pm    
Sorry about the requirements. I have "type" as P, S and I. If Type is P and S, I have to take record for P. If Type is S and I then take S. In all other cases take P.

Thanks for your help.
Hi, Use below query

SQL
Select Number,Email,Type from TableName where Number in (Select min(Number) from TableName group by Number)


It will solve your problem.

Don't forget to mark, if it is your solution.:-)
 
Share this answer
 
Comments
vasini 22-Feb-12 12:46pm    
It did not work out. It is displaying all the records.
Sarvesh Kumar Gupta 23-Feb-12 0:42am    
OK, Sorry for that, i not checked. very very sorry
try..this stored procedure it works..
CREATE PROCEDURE Test_Test
@G1 CHAR(10),
@G2 CHAR(10),
@G3 CHAR(10)
AS

IF( @G1='P' AND @G2='S')
SELECT * FROM dbo.test_Now WHERE Groups='P'
ELSE IF( @G2='S' AND @G3='I')
SELECT * FROM dbo.test_Now WHERE Groups='S'
ELSE
SELECT * FROM dbo.test_Now WHERE Groups='P'
GO
 
Share this answer
 
SELECT DISTICT(Number),Email,Type
FROM [DB0].[TABLE_NAME]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900