美好的一天,
我有以下两个表:
tMaster
TruckID TruckRegisterName
------------------------------
1 DL 1LK8520
2 DL 4XB9634
3 DL 1FH4253
4 DL 9EA1539
5 DL 1XV5408

DailyCons
TruckID TripDate DieselConsumed
---------------------------------------------
1 22-Nov-14 396.0
1 1-Nov-14 743.0
4 11-Nov-14 226.0
2 16-Nov-14 556.0
5 30-Nov-14 745.0
4 3-Nov-14 357.0
1 14-Nov-14 459.0
3 10-Nov-14 142.0
2 4-Nov-14 855.0
3 23-Nov-14 393.0
4 19-Nov-14 680.0
5 14-Nov-14 416.0
2 18-Nov-14 800.0
2 16-Nov-14 996.0
4 25-Nov-14 236.0
5 18-Nov-14 126.0
3 3-Nov-14 901.0

我被要求有以下输出
-----------------------------------------------------------------------------
TruckID
----------------------------------------------------------------------------
Date 1 2 3 4 5
-----------------------------------------------------------------------------
1-Nov-14 743.0
3-Nov-14 901.0 357.0
4-Nov-14 855.0
10-Nov-14 142.0
11-Nov-14 226.0
14-Nov-14 459.0 416.0
16-Nov-14 1552.0
18-Nov-14 800.0 126.0
19-Nov-14 680.0
22-Nov-14 396.0
23-Nov-14 393.0
25-Nov-14 236.0
30-Nov-14 745.0

据我所知,以上将基于PIVOT功能,但不知道如何去做。最重要的是,我被告知我必须使用聚合函数,但我的输出没有涉及任何计算。 感谢上面的任何帮助。
答案 0 :(得分:0)
您需要的只是conditional SUM
SELECT TripDate,
Sum(CASE WHEN TruckID = 1 THEN DieselConsumed END) [1],
Sum(CASE WHEN TruckID = 2 THEN DieselConsumed END) [2],
Sum(CASE WHEN TruckID = 3 THEN DieselConsumed END) [3],
Sum(CASE WHEN TruckID = 4 THEN DieselConsumed END) [4],
Sum(CASE WHEN TruckID = 5 THEN DieselConsumed END) [5]
FROM DailyCons
GROUP BY TripDate
或使用Pivot
SELECT *
FROM (SELECT *
FROM DailyCons)a
PIVOT (Sum(DieselConsumed)
FOR TruckID IN([1],
[2],
[3],
[4],
[5])) piv