简体   繁体   中英

pivoting a sql query going from wide to long format in ORACLE

I have a sql query like this

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

Thank you.

Using 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. 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM