如何在最终查询中添加具有空数据的行?

时间:2018-11-14 10:39:37

标签: clickhouse

我有一张带有数据的表:

table1
country  date       price

  USA    2001-01-25   2
  RUS    2001-01-25   17
  GER    2001-01-25   30
  USA    2001-02-25   11
  RUS    2001-02-25   22
  RUS    2001-02-26   25

我可以让所有国家都拥有

SELECT DISTINCT country FROM table1;

country 
  USA 
  RUS
  GER

并获取该月的所有价格

SELECT sum(price), country FROM table1 WHERE date >= '2001-02-01' AND date < '2001-03-01' GROUP BY country, price;

sum(price) country
   11        USA
   47        RUS

但是我也想为国家(GER)看到一行

sum(price) country
   11        USA
   47        RUS
    0        GER

如何在Clickhouse中轻松实现?

1 个答案:

答案 0 :(得分:2)

使用条件聚合:

SELECT
    country,
    SUM(CASE WHEN date >= '2001-02-01' AND date < '2001-03-01'
             THEN price ELSE 0 END) AS prices
FROM table1
GROUP BY country;

您当前的WHERE条款存在的问题是,它将过滤掉在2001年2月完全没有匹配价格的国家/地区。

如果上述解决方案无效,我们可以将其写为包含所有国家/地区到table1的表的联接:

SELECT c.country, COALESCE(t.prices, 0) AS prices
FROM (SELECT DISTINCT country FROM table1) c
LEFT JOIN
(
    SELECT country, SUM(prices) AS prices
    FROM table1
    WHERE date >= '2001-02-01' AND date < '2001-03-01'
    GROUP BY country
) t
    ON c.country = t.country;