Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first record out of each group from the result retrieved by using group by command

Suppose if my Input is:

ID  GroupID  Qty
1         1  100
2         1  200
3         1  300
4         2  98
5         2  198
6         3  175
7         3  275
8         3  375
9         4  215

Output should be

ID   GroupID    Qty
 1         1    100
 4         2    98
 6         3    175
 9         4    215

Can any one help me how to do it with SQL Server T-SQL query?

like image 467
SKumar Avatar asked Mar 07 '11 20:03

SKumar


3 Answers

declare @T table (ID int, GroupID int, Qty int)
insert into @T values
(1, 1, 100),
(2, 1, 200),
(3, 1, 300),
(4, 2, 98),
(5, 2, 198),
(6, 3, 175),
(7, 3, 275),
(8, 3, 375),
(9, 4, 215)

;with cte as
(
  select
    ID,
    GroupID,
    Qty,
    rank() over(partition by GroupID order by ID) as rn
  from @T
)  
select ID, GroupID, Qty
from cte
where rn = 1
like image 165
Mikael Eriksson Avatar answered Oct 23 '22 17:10

Mikael Eriksson


EDIT

SELECT 
    MIN(ID) ,
    GroupID,
    (SELECT TOP 1 Qty FROM @TABLE T2 WHERE T2.ID = MIN(T1.ID))
FROM 
    @TABLE T1
GROUP BY
    GroupID

Input

 ID GroupID   Qty
    1   1   100
    2   1   200
    3   1   300
    4   2   98
    5   2   198
    6   3   175
    7   3   275
    8   3   375
    9   4   215

Output

1   1   100
4   2   98
6   3   175
9   4   215
like image 6
PMC Avatar answered Oct 23 '22 17:10

PMC


The best and more flexible way in my opinion would be to use ROW_NUMBER(). The below I've tested for your example, just replace tmpTable with your table name:

SELECT a.* FROM tmpTable a INNER JOIN 
(SELECT    ROW_NUMBER() over(PARTITION BY GroupID ORDER BY ID, GroupID) AS SEQ, tmpTable.*
FROM            tmpTable) b
ON a.ID = b.ID AND a.GroupID = b.GroupID
WHERE b.SEQ = 1

read more about how to use ROW_NUMBER: https://learn.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql

like image 3
Richard Mneyan Avatar answered Oct 23 '22 17:10

Richard Mneyan