如果值不存在,如何连接两个表并返回0?

时间:2016-02-12 05:45:02

标签: sql join sqlite jointable

我有两张桌子hoursmessages

hours表只有一列hour,插入了0~23个值。

messages表也有hour列。

我试图加入这些表格。但是我的查询不起作用。

select hours.hour,ifnull(count(*),0) from hours left join messages on messages.hour = hours.hour group by hours.hour

样本数据在这里

讯息表

id    text         sender    datetime                     hour
1     Hi, John     Amy       2015-12-10 13:37:25 +0000    13
2     Yup          Mike      2015-12-10 15:49:11 +0000    15
3     you there?   Mike      2015-12-10 15:49:34 +0000    15

小时表

hour
0
1
2
3
4
..
23

我的查询结果

hour    ifnull(count(*),0)
0       1
1       1
2       1
3       1
4       1
...
13      1
14      1
15      2
...
24      1

我想要什么

hour    ifnull(count(*),0)
0       0
1       0
2       0
3       0
...
13      1
14      0
15      2
...
24      0

如何加入两个表并获得上述结果?

1 个答案:

答案 0 :(得分:0)

使用CASE Con​​dition和Full Join我们可以实现这个目标

DECLARE  @Table1 TABLE 
    (id int, text varchar(8), sender varchar(4), datetime varchar(25), hour int)
;

INSERT INTO @Table1
    (id, text, sender, datetime, hour)
VALUES
    (1, 'Hi, John', 'Amy', '2015-12-10 13:37:25 +0000', 13),
    (2, 'Yup', 'Mike', '2015-12-10 15:49:11 +0000', 15)
;

DECLARE @Table2  TABLE 
    (hour int)
;

INSERT INTO @Table2
    (hour)
VALUES
    (0),
    (1),
    (2),
    (3),
    (4),
    (6),
    (7),
    (8),
    (9),
    (13),
    (15),
    (16),
    (23)
;

   Select T.hour,
CASE WHEN cnt <> 0 THEN 
ROW_NUMBER()OVER(PARTITION BY T.cnt 
    ORDER BY (SELECT NULL)) 
ELSE CNT END cnt from (
select TT.hour,
CASE WHEN ISNULL(T.hour,0)<> 0 
THEN 1 ELSE ISNULL(T.hour,0) 
    END cnt  
        from @Table1  T
    FULL JOIN @Table2 TT
    ON TT.hour = T.hour

)T
ORDER BY T.hour