简体   繁体   English

SQL/Postgres 按后备分组并计数?

[英]SQL/Postgres group by and count with fallback?

Let's say I have a table things with 3 columns, id , animal and color .假设things有一个包含 3 列的表格, idanimalcolor For each row animal always has a value and color sometimes has a value.对于每一行, animal总是有一个值,而color有时也有一个值。 I need to count how many of each color , and for those rows without color , how many of each animal .我需要计算每种color有多少,对于那些没有color的行,每种animal有多少。 Is this possible with one query?这可以通过一个查询来实现吗? Would look like:看起来像:

  things  
   id  | animal  |  color  |
    1     dog         black
    2     cat         black
    3     dog          null
    4     cat          null

I would want to get back essentially: black: 2, cat: 1 and dog: 1我想基本上回来: black: 2, cat: 1 and dog: 1

You can do this with a UNION.您可以使用 UNION 执行此操作。

I would advise adding a literal column which specifies which result set it is.我建议添加一个文字列,指定它是哪个结果集。 This way, you can see what came from where.这样,您就可以看到来自哪里。

You can just delete the ThingType columns if you don't need them.如果不需要,您可以删除 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM