我尝试将小时数作为行数并将其按月拆分为列,以获得最终结果:
Hours Jan Feb Mar
08:00 To 08:59 1000 3500 2000
09:00 To 09:59 5000 6000 12000
ect ....................
我解决的字段是DateTime,其值为:
2014-01-01 08:02:34.000
我通过查询尝试:
SELECT EntryDate, sum(LTOT) AS InvoiceTotal,
sum(DATEPART(SECOND, EntryDate) + 60 *
DATEPART(MINUTE, EntryDate) + 3600 *
DATEPART(HOUR, EntryDate)
) as 'TotalTime'
FROM AZTRH WHERE TR_TY = '102' AND
LOC = '011' AND
(CAST(AZTRH.EntryDate AS DATE) BETWEEN '2014-01-01' AND '2014-01-02') AND
(CAST(AZTRH.EntryDate AS TIME) BETWEEN '08:00:00.000' AND '09:59:59.000')
GROUP BY AZTRH.EntryDate, LTOT
ORDER BY EntryDate
所以请问我怎么能得到我需要的结果?
答案 0 :(得分:0)
尝试以下查询:
;WITH PivotSource
AS (
SELECT DATEPART(HOUR, t.EntryDate) AS EntryHour,
MONTH(t.EntryDate) AS EntryMonth,
t.LTOT
FROM ...
WHERE ...
)
SELECT STR(p.EntryHour, 2, 0) + ':00 To' + STR(p.EntryHour, 2, 0)+':59' AS [Hours],
p.[1] AS Jan,
p.[2] AS Feb,
...
FROM PivotSource AS s
PIVOT( SUM(s.LTOT) FOR s.EntryMonth IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]) ) AS p
它使用:
DATEPART(HOUR, D/T value)
从MONTH(D/T value)
到提取月份编号(1,2,...,12),SUM
。