MYSQL:在空值

时间:2016-07-19 13:34:21

标签: mysql sql

我目前有以下声明:

SELECT hl.hour, hl.hourlistex, HOUR(ts.`Timestamp`) as Hour, COUNT(DISTINCT ts.`ForsNr`) as Count, SUM(ts.`TotalAmount`) as SumByReceipt
FROM hourlist hl
LEFT JOIN transactions ts on hl.hour = HOUR(ts.`Timestamp`) AND ts.`SoldDate` = '2016-07-12'
GROUP by hl.hour

结果:

hour    hourlistex  Hour    Count   SumByReceipt
9         9-10      NULL       0    NULL
10        10-11     NULL       0    NULL
11        11-12     NULL       0    NULL
12        12-13     12         2    152.0000
13        13-14     NULL       0    NULL
14        14-15     14         7    545.0000
15        15-16     15         8    843.0000
16        16-17     16         9    492.0000
17        17-18     17         12   868.0000
18        18-19     18         5    448.0000
19        19-20     NULL       0    NULL
20        20-21     NULL       0    NULL
21        21-22     NULL       0    NULL
22        22-23     NULL       0    NULL

我正在寻找一种方法来获得结果,没有起始和结束的NULL,但包括NULL。

像:

hour    hourlistex  Hour    Count   SumByReceipt
12        12-13     12         2    152.0000
13        13-14     NULL       0    NULL
14        14-15     14         7    545.0000
15        15-16     15         8    843.0000
16        16-17     16         9    492.0000
17        17-18     17         12   868.0000
18        18-19     18         5    448.0000

使用Mysql语句可以实现吗?我熟悉BETWEEN参数,但不知道它是否适用于我的情况。

1 个答案:

答案 0 :(得分:0)

这有点棘手,但您可以使用单独的join

来完成
SELECT hl.hour, hl.hourlistex, HOUR(ts.`Timestamp`) as Hour, COUNT(DISTINCT ts.`ForsNr`) as Count, SUM(ts.`TotalAmount`) as SumByReceipt
FROM hourlist hl LEFT JOIN
     transactions ts
     on hl.hour = HOUR(ts.`Timestamp`) AND ts.`SoldDate` = '2016-07-12' CROSS JOIN
     (SELECT max(hour(ts.timestamp)) as maxtsh, min(hour(ts.timestamp)) as mintsh
      FROM transactions ts
      WHERE ts.`SoldDate` = '2016-07-12'
     ) tts
WHERE h1.hour >= tts.mintsh and h1.hour < tts.maxtsh + 1 
GROUP by hl.hour;

tts派生表聚合事务以获取该日期的最早和最晚时刻。