我有客户,他们在几天或几周内存储数据。但客户只能选择在几天或一周内存储数据。见下面的例子
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
现在,我必须将基于客户ID 的时间总计为过去52周至27周和27周才能出现。
实施例: 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
查找已存储的总时数答案 0 :(得分:1)
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;