25

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.

Vijay
  • 563
  • 1
  • 6
  • 18

2 Answers2

45

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

Rachcha
  • 8,486
  • 8
  • 48
  • 70
0

I'm having a little trouble understanding the question so if I'm off I'll edit it after, but it looks like you want to do something like SELECT * FROM SM_SalesRepWorkflow WHERE Workflowid = latest where latest is the id of the workflow. Perhaps you can determine the latest outside of the query and bring that in instead of doing it from the query?

László Papp
  • 51,870
  • 39
  • 111
  • 135
BWStearns
  • 2,567
  • 2
  • 19
  • 33
  • 4
    This is more of a comment than an answer. Please avoid doing this lest your posts will get flagged. – Rachcha Jan 06 '14 at 04:38
  • I gave an answer I thought addressed the question but also asked OP to reclarify. It seemed wasteful to post a comment expressing confusion and then an overly certain answer. – BWStearns Jan 16 '14 at 17:04