postgresql 计算具有特殊列的行

问题描述

我的桌子是这样的:

表 1:

ident A B C D
1 2 1
2 3
3 1 2 1 5
4 4
5 4 1 3
6 3 2
7 3
8 1
9 1

现在我需要从该表中进行分析。 它应该看起来像:

表 2:

名称 just_name
A 3
B 1
C 1
D 0

just_name 列计算 table1 中除 ident 列之外的其他列中没有其他条目的列。 在实际表中,有超过 4 列,所以我最好不要为其他列使用 where。 :)

谢谢

解决方法

我会将其作为列来执行:

select count(*) filter (where A is not null and B is null and C is null and d is null),count(*) filter (where A is null and B is not null and C is null and d is null),count(*) filter (where A is null and B is null and C is not null and d is null),count(*) filter (where A is null and B is null and C is null and d is not null)       
from t;

您也可以将其表示为:

select c.colname,count(*) filter (where c.num_vals = 1)
from t cross join lateral
     (select colname,count(colval) over () as num_vals
      from (values ('a',t.a),('b',t.b),('c',t.c),('d',t.d)) v(colname,colval)
      group by colname
     ) c
group by c.colname;

这将返回单独行中的值。而且更容易概括。

,

如果您只需将列名放在列列表中就可以了,那么下面的查询可以获得您想要的结果。虽然可以使这些部分动态化,但如果您知道列名并且它没有动态更改,这将是更好的方法。如果你想要帽子部分动态olso,请告诉我。

架构:

create table mytable1(ident int,A int,B int,C int,D int);
insert into mytable1 values(1,null,2,1,null);
insert into mytable1 values(2,3,null);
insert into mytable1 values(3,5);
insert into mytable1 values(4,4,null);
insert into mytable1 values(5,3);
insert into mytable1 values(6,null);
insert into mytable1 values(7,null);
insert into mytable1 values(8,null);
insert into mytable1 values(9,null);

查询:

with cte as (SELECT
   unnest(array['A','B','C','D']) AS Columns,unnest(array[A,B,C,D]) AS Values,row_number()over(order by 1)rn
FROM mytable1),cte2 as (
select rn,max(cte.columns)col,count(*) from cte   
 where values is not null
group by rn
having count(*)=1)
select distinct columns as name,coalesce(just_name,0)  from  cte left join (select col,count(rn) just_name from cte2
group by col)t on cte.columns=t.col

输出:

名称 合并
A 3
C 1
D 0
B 1

dbfiddle here