简体   繁体   English

postgres 计算来自多列的不同值

[英]postgres count distinct values from multiple column

I am trying to display all different values from 3 columns and the amount of them.我正在尝试显示 3 列中的所有不同值及其数量。

My table:我的表:

date |  col1  |  col2  | col3
-------------------------------
26...|  a     |  a     | b
25...| c      |  d     |  a
...

All 3 columns have the values a, b, c, d.所有 3 列都具有值 a、b、c、d。

I would like to have something like this:我想要这样的东西:

date   |  col  |  a  | b   |  c  |   d 
--------------------------------------
26.....| col1  |  1  |  0  |  0  |  0
26.....| col2  |  1  |  0  |  0  |  0
26.....| col3  |  0  |  1  |  0  |  0
25.....| col1  |  0  |  0  |  1  |  0
25.....| col2  |  0  |  0  |  0  |  1

Is there a way to do it?有没有办法做到这一点?

Welcome to SO.欢迎来到 SO。 Assuming that the possible values are fixed ( a , b , c and d ), an alternative is to create a row for each column and date in a CTE and in the outer query count them with a FILTER , eg假设可能的值是固定的( abcd ),另一种方法是为CTE中的每一列和日期创建一行,并在外部查询中使用FILTER对它们进行计数,例如

WITH j (date,col) AS (
  SELECT date, unnest(array[col1,col2,col3])
  FROM mytable
)
SELECT j.date, 'col'||j.col, 
 count(*) FILTER (WHERE col ='a'), 
 count(*) FILTER (WHERE col ='b'),
 count(*) FILTER (WHERE col ='c'),
 count(*) FILTER (WHERE col ='d') 
FROM j
JOIN mytable t ON t.date = j.date
GROUP BY j.date,j.col
ORDER BY j.date,j.col;

Demo: db<>fiddle演示: db<>fiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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