Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Get first record value from each group using T-SQL

$
0
0

Hi All,

I have one table with 3 columns, say Name  as varchar, ID1 as int, ID2 as int datatypes.

Create table:

Create table Sample
(
 Rec_Id Int Not null,
 Name varchar(30) null,
 ID1 int null,
 ID2 int null,
CONSTRAINT [PK_Sample] PRIMARY KEY NONCLUSTERED
(
 [Rec_Id] ASC
)


Insert Statement:

Insert into sample (Rec_ID,Name,ID1,ID2) values ( 1 ,'A',1,2)
 Insert into sample (Rec_ID,Name,ID1,ID2) values ( 2 ,'A', 2,3)
 Insert into sample (Rec_ID,Name,ID1,ID2) values ( 3 ,'A', 3 ,1)

 Insert into sample (Rec_ID,Name,ID1,ID2) values ( 4 ,'B', 1 , 2)
Insert into sample (Rec_ID,Name,ID1,ID2) values (  5 , 'B',  2 , 3)
Insert into sample (Rec_ID,Name,ID1,ID2) values (  6 , 'B' , 3 , null)

 Insert into sample (Rec_ID,Name,ID1,ID2) values ( 7 ,'C', 1 , 2)
 Insert into sample (Rec_ID,Name,ID1,ID2) values ( 8 ,'C' , 2 , 3)
 Insert into sample (Rec_ID,Name,ID1,ID2) values ( 9 ,'C' , 3 , 4)
 Insert into sample (Rec_ID,Name,ID1,ID2) values (10 ,'C' , 5 , 1 )

Insert into sample (Rec_ID,Name,ID1,ID2) values ( 11 ,'D', 2 , 3)
Insert into sample (Rec_ID,Name,ID1,ID2) values ( 12 , 'D', 3 , 4)
Insert into sample (Rec_ID,Name,ID1,ID2) values ( 13 , 'D' , 4 , 3)

My source data looks like this..

Rec_Id Name ID1   ID2
  1           A        1     2       
  2           A        2     3
  3           A        3     1

  4           B        1     2
  5           B        2     3
  6           B        3   null   --> Need to display this row in the output, because 1 is missing in ID2

  7           C        1     2
  8           C        2     3
  9           C        3     4
 10          C           1     --> Need to display this row in the output, because 4 is missing after 3 in ID1

 11          D        2     3
 12          D        3     4
 13          D        4     3   --> Need to display this row in the output, because 2 is missing in ID2


My Output should look like below:

Rec_Id  Name  ID1   ID2
6                B       3    
10              C       5      1
13              D       4      3

So, I need t-sql to get above output.

Thanks in advance,
RH


sql


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>