在sql中选择每个组的第一行 [英] Select First Row of Every Group in sql

查看:315
本文介绍了在sql中选择每个组的第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个桌子.

1-> SM_Employee

1-> SM_Employee

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

2-> SM_SalesRepWorkflow

2-> SM_SalesRepWorkflow

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

在这些表中,我需要根据CurrentMonth和CurrentYear的SalesRepId从SM_SalesRepWorkflow订单中选择每个SalesRep详细信息的第一行.

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

示例

Workflowid SalesRepId数量已分配数量左月年

Workflowid SalesRepId QuantityAssigned QuantityLeft Month Year

WF_101:EMP_101:100:90:五月:2013
WF_101:EMP_102:100:100:五月:2013
WF_101:EMP_103:100:80:五月:2013
WF_102:EMP_101:100:70:2013年5月:

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

所以我想要的结果是

WF_101:EMP_101:100:90:五月:2013
WF_101:EMP_102:100:100:五月:2013
WF_101:EMP_103:100:80:五月:2013

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

因此,SalesRep可能有许多工作流程. 但是我想要当前月和年中每个SalesRep的第一个.

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

推荐答案

您可以使用ROW_NUMBER()函数,如下所示:

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

这篇关于在sql中选择每个组的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆