Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select First Row of Every Group in sql [duplicate]

Tags:

I have two tables .

1-> SM_Employee

 (1) employeeid     (2) roleid  (3) storeid 

2-> SM_SalesRepWorkflow

 (1) workflowid  (2) Salesrepid   foreign key to employeeid  (3) QuantityAssigned  (4) QuantityLeft  (5) month   (6) year 

By these tables I need to select first row of every SalesRep Details from SM_SalesRepWorkflow order by SalesRepId for CurrentMonth and CurrentYear.

Example

Workflowid SalesRepId QuantityAssigned QuantityLeft Month Year

WF_101 : EMP_101 : 100 : 90 : May : 2013
WF_101 : EMP_102 : 100 : 100 : May : 2013
WF_101 : EMP_103 : 100 : 80 : May : 2013
WF_102 : EMP_101 : 100 : 70 : May : 2013

So result i want is

WF_101 : EMP_101 : 100 : 90 : May : 2013
WF_101 : EMP_102 : 100 : 100 : May : 2013
WF_101 : EMP_103 : 100 : 80 : May : 2013

So There can be many Workflow for a SalesRep. But i want the first one for every SalesRep for current month and year.

like image 352
Vijay Avatar asked May 13 '13 19:05

Vijay


People also ask

How do I select the first row in a GROUP BY a group?

To do that, you can use the ROW_NUMBER() function. In OVER() , you specify the groups into which the rows should be divided ( PARTITION BY ) and the order in which the numbers should be assigned to the rows ( ORDER BY ).

How do I get the first record of each group in SQL?

The first way to find the first row of each group is by using a correlated subquery. In short, a correlated subquery is a type of subquery that is executed row by row. It uses the values from the outer query, that is, the values from the query it's nested into.

How do you select only the first rows for each unique value of a column in SQL?

Adding the DISTINCT keyword to a SELECT query causes it to return only unique values for the specified column list so that duplicate rows are removed from the result set.


1 Answers

You can use the ROW_NUMBER() function like this:

SELECT *   FROM(SELECT workflowid, salesRepId, quantityAssigned,               quantityLeft, month, year               , ROW_NUMBER()                 OVER (PARTITION BY salesRepId                           ORDER BY workflowid) AS rownumber          FROM sm_salesRepWorkflow)  WHERE rownumber = 1; 

Fiddle Demo

like image 150
Rachcha Avatar answered Sep 20 '22 01:09

Rachcha