簡體   English   中英

在ORACLE中將SQL查詢從寬格式轉換為長格式

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

我有這樣的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

結果就像

group  typea    typeb
 1      10         30
 2      20          40

效果很好,但我需要這樣的結果:

group  types     value
1       typea     10
2       typea      30
1       typeb      20
2       typeb      40

有沒有辦法修改此查詢:

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

這樣它將返回我需要的結果?

注意-正在使用ORACLE

謝謝。

使用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"

數據已經正確組織,您只需要進行不同的分組即可。

SELECT "group", 'type'||field1 as Types, sum(1) as value
FROM mytable
GROUP BY "group", 'type'||field1
ORDER BY Types, "group"

注釋組是一個保留字,因此如果可以將其列和類型重命名,則將其放在“”中,長期來看會更好,因為一個是保留字,另一個是關鍵字。

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

盡管為什么需要將“類型”作為字段1的前綴,這很奇怪。 這可能只是一個簡單的(無關鍵性的)計數,並且似乎僅需分組。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM