创建月度报告

时间:2018-07-07 17:11:45

标签: sql sqlite

我正在创建月度报告,并且有一张桌子:

DriverName    TodayDate     WeekNo    KM
----------    ----------    ------    ---
ALI           02-01-2018    1         2
ALI           04-01-2018    1         4
ALI           08-01-2018    2         3
ALI           09-01-2018    2         8
AHMED         05-02-2018    1         9
AHMED         05-02-2018    1         9
...
So on

我正在尝试如下结果:

DriverName    KM/W1  KM/W2  KM/W3  KM/W4  KM/W5   Total
----------    -----  -----  -----  -----  -----   -----
ALI           6      11     0      0      0       17
AHMED         18     0      0      0      0       18

我已经尝试过,但是不知道如何编写内部选择查询:

Select DriverName,(Select KM FROM Traveling Where WeekNo=1) as KM/W1, ... Where Traveling

任何人都请帮忙!谢谢!

1 个答案:

答案 0 :(得分:1)

希望这会有所帮助:

SELECT drivername, 
       Sum(CASE 
             WHEN weekno = 1 THEN km 
             ELSE 0 
           END) AS wk1km, 
       Sum(CASE 
             WHEN weekno = 2 THEN km 
             ELSE 0 
           END) AS wk2km, 
       Sum(CASE 
             WHEN weekno = 3 THEN km 
             ELSE 0 
           END) AS wk3km, 
       Sum(CASE 
             WHEN weekno = 4 THEN km 
             ELSE 0 
           END) AS wk4km, 
       Sum(CASE 
             WHEN weekno = 5 THEN km 
             ELSE 0 
           END) AS wk5km, 
       Sum(km)  AS total 
FROM   (SELECT drivername, 
               weekno, 
               Sum(km) km 
        FROM   traveling 
        GROUP  BY drivername, 
                  weekno) AS t 
GROUP  BY drivername 
ORDER  BY total; 

这里是要测试的示例sqlfiddle

演示的快照运行:

enter image description here