如何 return 在 postgresql 中使用过滤器列出类型?

how to return list type with filter in postgresql?

我希望我的查询在每一列都给出 YES 时给我类型列表。

table 看这个:

a      b     c     d     no
yes   null  yes   null   1
null  yes   yes   null   2
yes   null  null  yess   3

所需的查询结果:

no   type
1     a
1     c
2     b
2     c
3     a
3     d

我应该如何编写查询以获得预期结果?

提前致谢。

查看 pivot tables 或合并多个查询:

SELECT no,'a' AS type FROM t WHERE a IS NOT NULL
UNION SELECT no,'b' FROM t WHERE b IS NOT NULL
UNION SELECT no,'c' FROM t WHERE c IS NOT NULL
UNION SELECT no,'d' FROM t WHERE d IS NOT NULL
ORDER BY no,type

编辑(见评论):

SELECT no,'a' AS type FROM t WHERE a = 'yes'
UNION SELECT no,'b' FROM t WHERE b = 'yes'
UNION SELECT no,'c' FROM t WHERE c = 'yes'
UNION SELECT no,'d' FROM t WHERE d = 'yes'
ORDER BY no,type;

演示:db<>fiddle

作为替代方案,您可以使用 unnest:

WITH cte as
(SELECT no, 
unnest(array['a', 'b', 'c', 'd']) as type,
unnest(array[a, b, c, d]) as colvalue
from abcdtypes)
SELECT no, type 
FROM cte 
where colvalue = 'yes'
ORDER BY 1, 2;

它可以工作并且可以说更优雅。但如果有很多列,我只会做这样的事情。对于你例子中的四个,我也站在吉姆琼斯一边。