我有以下查询按周(周日至周六)分组,并进行必要的计算。输出显然给出了一年中的周数。作为第一步,我可以将这些数据存储在一个表中,然后当我想使用这些数据时,我想将周数转换为实际的日期范围。以下是查询。
SELECT
DATEPART(WW,aa.Time) ddtt ,bb.Nd ,'Percentages' Report
,case when SUM(ZZ) = 0 then 0 else convert(decimal(18,3),SUM((CCC+PSY))*100/SUM(ZZ)) end Cond1
,case when SUM(ZZ) = 0 then 0 else convert(decimal(18,3),SUM(USN)*100/SUM(ZZ)) end Cond2
FROM db2000.dbo.Table aa join db2000.dbo.List bb on aa.Device = bb.DeviceID
where aa.Time between '2013/12/15' AND '2014/1/15 23:00' and Nd like '_s1'
group by bb.Nd ,DATEPART(WW,aa.Time)
order by ddtt
此查询的输出是
ddtt Nd Report Cond1 Cond2 1 21S Percentages 94.787 63.998 1 41S Percentages 94.592 63.473 1 61S Percentages 94.356 65.845 2 21S Percentages 93.802 64.594 2 41S Percentages 94.141 65.486 2 61S Percentages 93.849 66.144 3 21S Percentages 94.572 65.940 3 41S Percentages 95.123 67.261 3 61S Percentages 95.044 67.211 51 21S Percentages 94.042 65.245 51 41S Percentages 94.857 65.847 51 61S Percentages 94.036 67.019 52 21S Percentages 94.592 65.469 52 41S Percentages 95.071 66.159 52 61S Percentages 93.932 66.989 53 21S Percentages 94.786 65.391 53 41S Percentages 95.266 66.883 53 61S Percentages 94.526 67.504
我希望列ddtt的值代表实际日期,例如。 05/01/2014 - 11/01/2014。完成此操作的单独查询也可以。
答案 0 :(得分:0)
根据您可以使用的周数,从周日到周六获取日期
SELECT dateadd(dd, -datepart(wk, '2014-01-08') - 1
, dateadd(ww, @weeknum, '2014-01-01'))
, dateadd(dd, -datepart(wk, '2014-01-08') - 2
, dateadd(ww, @weeknum + 1, '2014-01-01'))
其中@weeknum
是周数,对于我使用datepart(wk, '2014-01-08')
的星期几,因为无论实际的星期日如何,使用1月的第一天将始终返回1。
您的查询将变为
SELECT DATEADD(dd, -DATEPART(wk, '2014-01-08') - 1
, DATEADD(ww, DATEPART(WW,aa.Time), '2014-01-01'))
, DATEADD(dd, -DATEPART(wk, '2014-01-08') - 2
, DATEADD(ww, DATEPART(WW,aa.Time) + 1, '2014-01-01'))
, bb.Nd
, 'Percentages' Report
, CASE WHEN SUM(ZZ) = 0 THEN 0
ELSE convert(decimal(18,3),SUM((CCC+PSY))*100/SUM(ZZ))
END Cond1
, CASE WHEN SUM(ZZ) = 0 THEN 0
ELSE convert(decimal(18,3),SUM(USN)*100/SUM(ZZ))
END Cond2
FROM db2000.dbo.Table aa
JOIN db2000.dbo.List bb ON aa.Device = bb.DeviceID
WHERE aa.Time BETWEEN '2013/12/15' AND '2014/1/15 23:00' AND Nd LIKE '_s1'
GROUP BY bb.Nd ,DATEPART(WW,aa.Time)
ORDER BY ddtt
或类似的东西,如果你想在字符串中加入两个日期。