[英]SQL/Postgres group by and count with fallback?
假设things
有一个包含 3 列的表格, id
, animal
和color
。 对于每一行, animal
总是有一个值,而color
有时也有一个值。 我需要计算每种color
有多少,对于那些没有color
的行,每种animal
有多少。 这可以通过一个查询来实现吗? 看起来像:
things
id | animal | color |
1 dog black
2 cat black
3 dog null
4 cat null
我想基本上回来: black: 2, cat: 1 and dog: 1
您可以使用 UNION 执行此操作。
我建议添加一个文字列,指定它是哪个结果集。 这样,您就可以看到来自哪里。
如果不需要,您可以删除 ThingType 列。
SELECT
-- My addition - delete if not wanted
'ByColor' as ThingType,
color as ThingCounted,
COUNT(DISTINCT animal) AS ThingCount
FROM
things
GROUP BY
color
UNION
SELECT
-- My addition - delete if not wanted
'ByAnimal' as ThingType,
animal as ThingCounted,
COUNT(DISTINCT animal) AS ThingCount
FROM
things
GROUP BY
animal
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.