首页 > 解决方案 > 在 SQL 中,通过转置列结果来查询表

问题描述

背景

原谅这个问题的标题,因为我不确定如何描述我正在尝试做的事情。

我有一个 SQL 表,d看起来像这样:

+--+---+------------+------------+
|id|sex|event_type_1|event_type_2|
+--+---+------------+------------+
|a |m  |1           |1           |
|b |f  |0           |1           |
|c |f  |1           |0           |
|d |m  |0           |1           |
+--+---+------------+------------+

问题

我正在尝试编写一个查询,该查询产生以下计数event_type_1event_type_2剪切(分组?)的摘要sex

+-------------+-----+-----+
|             |  m  |  f  |
+-------------+-----+-----+
|event_type_1 |  1  |  1  |
+-------------+-----+-----+
|event_type_2 |  2  |  1  |
+-------------+-----+-----+

问题是,这似乎涉及将 2event_type列转换为查询结果的行,这是我作为 SQL 新手用户不熟悉的。

我试过的

到目前为止,我提出了以下查询:

SELECT event_type_1, event_type_2, count(sex)
FROM d
group by event_type_1, event_type_2

但这只给了我这个:

+------------+------------+-----+
|event_type_1|event_type_2|count|
+------------+------------+-----+
|1           |1           |1    |
|1           |0           |1    |
|0           |1           |2    |
+------------+------------+-----+

标签: sqlpostgresqlsqldf

解决方案


您可以使用 alateral join取消透视数据。然后使用条件聚合计算mf

select v.which,
       count(*) filter (where d.sex = 'm') as m,
       count(*) filter (where d.sex = 'f') as f
from d cross join lateral
     (values (d.event_type_1, 'event_type_1'),
             (d.event_type_2, 'event_type_2')
     ) v(val, which)
where v.val = 1
group by v.which;

是一个 db<>fiddle。


推荐阅读