我有一些客户,他们以天或周为单位存储数据。但客户只能选择按天或按周存储数据。请看下面的例子
ClientID StoreID period hours
1 10 2010-04-19 8.04
1 10 2010-04-20 6.24
1 10 2010-04-21 8.26
1 20 2010-04-22 7.94
1 20 2010-04-23 22.43
1 20 2010-04-24 22.99
2 5 2010-12-19 130.67
2 5 2010-12-26 159.26
2 5 2011-01-02 113.59
2 5 2011-01-09 12.66
2 8 2011-01-16 22.34
2 8 2011-01-23 11.35
现在我必须根据过去 52 周至 27 周以及 27 周的客户 ID 期间的小时数进行汇总。
示例:
ClientId =1 从过去 52 周到 27 周总小时数 = 150
ClientId =1 从过去 27 周到今天的总小时数 = 200
ClientId =2 从过去 52 周到 27 周总小时数 = 350
ClientId =2 从过去 27 周到今天的总小时数 = 250。
如何用 T-SQL 编写这个?
还有另一个这样的客户时间级别表。
Client time_level
1 Day
2 Week
更新:我们需要根据@clientid找到storedid的总小时数
DECLARE @MondayThisWeek DATETIME
SELECT @MondayThisWeek = DATEADD(wk,
DATEDIFF(wk, 0, GETDATE()),
0);
DECLARE @ClientId INT;
SELECT @ClientId = 1;
SELECT cd.StoreId,
SUM(cd.HOURS) AS Hours
FROM ClientData cd
WHERE cd.Date >= DATEADD(ww, -52, @MondayThisWeek)
AND cd.Date < DATEADD(ww, -27, @MondayThisWeek)
AND cd.ClientId = @ClientId
GROUP BY cd.StoreId;
SELECT cd.StoreId,
SUM(cd.HOURS) AS Hours
FROM ClientData cd
WHERE cd.Date >= DATEADD(ww, -27, @MondayThisWeek)
AND cd.Date < @MondayThisWeek
AND cd.ClientId = @ClientId
GROUP BY cd.StoreId;