sql - 在 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_1
和event_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 |
+------------+------------+-----+
解决方案
您可以使用 alateral join
取消透视数据。然后使用条件聚合计算m
和f
:
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。
推荐阅读
- java - 使用 linearlayout.addView() 添加到线性布局的视图在运行时不会保持其顺序
- apache-spark - 在分区 Spark DataFrame 中使用多列是否会使读取速度变慢?
- http - 在 esp8266 中获取 http 请求需要帮助
- sql - 如何使用 sql 加入 2 个表(尝试内连接但没有得到我想要的结果)
- java - 如何从一组 Gradle java 任务中分解出一组 systemProperty 调用?
- r - 如何初始化空数据框,其中列数取决于R中的多个输入参数
- wordpress - 在wordpress中将www重定向到非www
- javascript - 如何在 SQL 中使用带有 CONVERT 的占位符?
- python - Pandas:多索引子集选择
- javascript - 如何更改 JavaScript 中既不是类也不是 id 的选择元素?