我正在尝试研究是否可以在SQL中进行以下转换:
+--------+--------+--------+
|POLICY_1|POLICY_2|POLICY_3|
+--------+--------+--------+
|T |T |F |
+--------+--------+--------+
|F |T |F |
+--------+--------+--------+
|T |T |T |
+--------+--------+--------+
是否可以查询此表并最终得到如下所示的结果集:
+------+-----+
|POLICY|COUNT|
+------+-----+
|1 |2 |
+------+-----+
|2 |3 |
+------+-----+
|3 |1 |
+------+-----+
我想知道一般的SQL术语,但是重要的是我正在使用Postgres(9.2)
答案 0 :(得分:2)
Union All,Aggregate和CASE Version
select 1 as POLICY, SUM(case when POLICY_1 = 'T' THEN 1 ELSE 0 end) as COUNT
from POLICIES
union all
select 2 as POLICY, SUM(case when POLICY_2 = 'T' THEN 1 ELSE 0 end) as COUNT
from POLICIES
union all
select 3 as POLICY, SUM(case when POLICY_3 = 'T' THEN 1 ELSE 0 end) as COUNT
from POLICIES
* Unpivot版本:* (MicroSoft T-SQL特定)
如果您坚持要将行转换为列,则可以使用PIVOT / UNPIVOT功能。
SELECT ROW_NUMBER() OVER (ORDER BY PolicyName) AS Row, *
FROM ( select SUM(CASE WHEN Policy_1 = 'T' THEN 1 ELSE 0 END) as Policy_1,
SUM(CASE WHEN Policy_2 = 'T' THEN 1 ELSE 0 END) as Policy_2,
SUM(CASE WHEN Policy_3 = 'T' THEN 1 ELSE 0 END) as Policy_3
from POLICIES
)p
UNPIVOT ( T_Count FOR PolicyName in ([Policy_1], [Policy_2], [Policy_3]))unpvt
Unnest版本(postgre sql特定)
所有学分转到 Francis ,主题播放者,我只是在这里发布。
select
UNNEST((select array_agg(generate_series)
from generate_series(1,3))) as policy_name,
UNNEST(array[
sum(case when policy_1 = 't' then 1 else 0 end),
sum(case when policy_2 = 't' then 1 else 0 end),
sum(case when policy_3 = 't' then 1 else 0 end)
]) as count from POLICY
答案 1 :(得分:0)
根据建议, 这是Postgresql的UNNEST版本:
select
UNNEST((select array_agg(generate_series) from generate_series(1,3))) as policy_name,
UNNEST(array[
sum(case when policy_1 = 't' then 1 else 0 end),
sum(case when policy_2 = 't' then 1 else 0 end),
sum(case when policy_3 = 't' then 1 else 0 end)
]) as count from POLICY