[英]pivoting a sql query going from wide to long format in ORACLE
I have a sql query like this 我有这样的SQL查询
select
group,
sum(case when field1 = 'a' then 1 else 0 end ) as typea,
sum(case when field1 = 'b' then 1 else 0 end ) as typeb
from mytable
group by group
results are like 结果就像
group typea typeb
1 10 30
2 20 40
That works fine but I need the results to be like this: 效果很好,但我需要这样的结果:
group types value
1 typea 10
2 typea 30
1 typeb 20
2 typeb 40
Is there a way to modify this query: 有没有办法修改此查询:
select
group,
sum(case when field1 = 'a' then 1 else 0 end ) as typea,
sum(case when field1 = 'b' then 1 else 0 end ) as typeb
from mytable
group by group
so that it will return the results I need? 这样它将返回我需要的结果?
NOTE -- am using ORACLE 注意-正在使用ORACLE
Thank you. 谢谢。
Using UNION ALL
: 使用
UNION ALL
:
select "group",
'typea' AS type,
sum(1) AS value
from mytable
where field1 = 'a'
group by "group"
UNION ALL
select "group",
'typeb',
sum(1)
from mytable
where field1 = 'b'
group by "group"
The data is already organized correctly you just need to group differently. 数据已经正确组织,您只需要进行不同的分组即可。
SELECT "group", 'type'||field1 as Types, sum(1) as value
FROM mytable
GROUP BY "group", 'type'||field1
ORDER BY Types, "group"
Note group is a reserved word so I put it in "" if the column for it and types could be renamed, you would be better off long term as one is a reserved word, the other is a key word. 注释组是一个保留字,因此如果可以将其列和类型重命名,则将其放在“”中,长期来看会更好,因为一个是保留字,另一个是关键字。
With MyTable("group",field1) as (select 1, 'a' from dual UNION ALL
select 1 , 'a' as field1 from dual UNION ALL
select 1 , 'b' as field1 from dual UNION ALL
select 1 , 'b' as field1 from dual UNION ALL
select 2 , 'a' as field1 from dual UNION ALL
select 2 , 'a' as field1 from dual UNION ALL
select 2 , 'a' as field1 from dual UNION ALL
select 2 , 'b' as field1 from dual)
SELECT "group", 'type'||field1 as Types, sum(1) as value
FROM mytable
GROUP BY "group", 'type'||field1
Though why you need to concat 'type' as a prefix to field1 is odd. 尽管为什么需要将“类型”作为字段1的前缀,这很奇怪。 It could just be a simple (no pivoting) count and group by seem to be all that's needed.
这可能只是一个简单的(无关键性的)计数,并且似乎仅需分组。
SELECT "group", field1 as Types, count(*) as value
FROM mytable
GROUP BY "group", field1
ORDER BY Types, "group"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.