row_number Over Partition

时间:2016-08-22 14:44:21

标签: sql-server-2008 row-number

我正在使用SQL Server 2008 R2。我有一个名为EmployeePurcheses的表,其中包含以下结构和示例数据:

EmployeeID Date Usd
1     2014-11-12 5
1     2014-11-18 9
1     2014-11-18 7

我要做的是在“日期”字段订购的每个日期列出该员工的工作周。因此,输出将如下所示:

rn EmployeeID Date WW
1  1     2014-11-12 46
2  1     2014-11-18 47
2  1     2014-11-18 47

我打算使用以下查询对数据进行分区,但失败了。提前谢谢你。

select 
        rn = ROW_NUMBER() over (partition by DATEPART(ww, [Date]) order by    
        DATEPART(ww, [Date]))
       ,[EmployeeID ]
       ,Cast([Date] as date) as [Date]
       ,DATEPART(ww, [Date]) as WW
FROM EmployeePurcheses 
Order by [Date] asc

1 个答案:

答案 0 :(得分:1)

根据您的结果,您需要DENSE_RANK()而不进行分区:

WITH EmployeePurchases AS
(
    SELECT * FROM (VALUES
    (1, '2014-11-12', 5),
    (1, '2014-11-18', 9),
    (1, '2014-11-18', 7)) T(EmployeeID, Date, Usd)
)
select 
        rn = DENSE_RANK() over (order by DATEPART(WW, [Date]))
       ,[EmployeeID]
       ,Cast([Date] as date) as [Date]
       ,DATEPART(ww, [Date]) as WW
FROM EmployeePurchases 
Order by [Date] asc