COUNT中没有零值,带有2个ORDER BY语句

时间:2015-10-23 10:42:31

标签: sql postgresql cross-join

我有3张桌子:

+---------+    +----------+    +----------+
|  kkw    |    |  block   |    |  status  |
+---------+    +----------+    +----------+
| kkw_id  |    | block_id |    |status_id |
| land_id |    | kkw_id   |    | ....     |
| ...     |    | status_id|    | ....     |
+---------+    +----------+    +----------+

我想显示每个国家/地区的块数(land_id)和状态,如果某个国家/地区没有与状态相对应的阻止,则为零。我尝试了这个请求,但没有显示零值:

SELECT s.status_id, k.land_id, COUNT(b.block_id)
FROM kkw_status AS s
LEFT JOIN block AS b ON s.status_id = b.status_id
LEFT JOIN kkw AS k ON b.kkw_id=k.kkw_id
GROUP BY s.status_id, k.land_id
ORDER BY k.land_id, s.status_id;

结果:

status_id   land_id count
    1          1      2
    4          1      3  ....

但我想:

status_id   land_id count
    1          1      2
    2          1      0
    3          1      0
    4          1      3  .....

有什么想法吗?感谢

1 个答案:

答案 0 :(得分:3)

您按k.land_id进行分组。因此,当某些内容不匹配时,此列的值为NULL。因此,零值只会出现在这些行上。

如果您想要所有status_idland_id,请使用cross join创建所有SELECT s.status_id, k.land_id, COUNT(b.block_id) FROM kkw_status s CROSS JOIN kkw k LEFT JOIN block b ON b.status_id = s.status_id AND b.kkw_id = k.kkw_id GROUP BY s.status_id, k.land_id ORDER BY k.land_id, s.status_id; 的列表,然后计算与每个组匹配的数字。我认为这就是查询的样子:

MyList