案例陈述给出了逐项错误

时间:2018-11-29 17:21:47

标签: sql conditional amazon-redshift

以下查询:

SELECT 
    CASE WHEN is_dog = 1 THEN COUNT(*) END AS dogs,
    CASE WHEN is_cats = 1 THEN count(*) END as cats
FROM 
    animals
WHERE
    birth_date >= '2018-01-01';

我收到此错误:

  

无效操作:“ is_dog”列必须出现在GROUP BY子句中或在聚合函数中使用

我需要对此进行哪些更改?我是使用redshift的新手。

3 个答案:

答案 0 :(得分:1)

应写为

SELECT count(*) FILTER (WHERE is_dog = 1) AS dogs,
       count(*) FILTER (WHERE is_cat = 1) AS cats
FROM animals
WHERE birth_date >= '2018-01-01';

答案 1 :(得分:1)

COUNT(*)表达式在不同的列或不同的CASE表达式中不会有所不同。它是一个行数,并且不会通过将其他条件置于 之外而不会更改。

此外,当您将所有行分组为一行时,除非引用位于聚合函数(例如{{ 1}}或is_cat

将这两个事实结合在一起,您 可以 做类似...的事情

  • is_dog

哪个给出类似...的查询

SUM()

或者,假设COUNT()SUM(CASE WHEN is_dog = 1 THEN 1 ELSE 0 END)字段仅包含SELECT SUM(CAST WHEN is_dog = 1 THEN 1 ELSE 0 END) AS dogs, SUM(CAST WHEN is_cat = 1 THEN 1 ELSE 0 END) AS cats FROM animals WHERE birth_date >= '2018-01-01'; is_cat,那么您甚至根本不需要is_dog表达式。 ..

0

答案 2 :(得分:0)

在Amazon Redshift上,您可能想要:

SELECT SUM(case when is_dog = 1 then 1 else 0 END) AS dogs,
       SUM(case when is_cats = 1 then then 1 else 0 end)  as cats
FROM animals
WHERE birth_date >= '2018-01-01';

或者,较短的形式是:

SELECT SUM( (is_dog = 1)::int ) AS dogs,
       SUM( (is_cats = 1)::int )  as cats
FROM animals
WHERE birth_date >= '2018-01-01';

或者如果列仅取0/1 / NULL,则:

SELECT SUM( is_dog ) AS dogs,
       SUM( is_cats )  as cats
FROM animals
WHERE birth_date >= '2018-01-01';