![](/img/trans.png)
[英]How Can I Flatten the Results of a SQL Query - Transposing Rows to Columns?
[英]How do I flatten results from my SQL Query?
我有一個查詢,返回下表:
Year IsFunded NotFunded 2003 Null 4 2003 3 Null 2004 Null 2 2004 8 Null
所以我需要:
SELECT Year, IsFunded, NotFunded FROM ( --myQuery that returns unflattened results )
每年只需要一行。 喜歡:
Year IsFunded NotFunded 2003 3 4 2004 8 2
使用GROUP BY
和MAX
:
SELECT t.Year, MAX(t.IsFunded) AS IsFunded, MAX(t.NotFunded) AS NotFunded
FROM
(
--myQuery that returns unflattened results
) AS t
GROUP BY t.Year;
我會在總和時將null替換為0,然后按年添加組,如下所示
with MyQuery(Year,IsFunded,NotFunded) as (
select 2003,Null,4 from dual union
select 2003,3,Null from dual union
select 2004,Null,2 from dual union
select 2004,8,Null from dual
)
select year,sum(case when IsFunded is null then 0 else IsFunded end) as IsFunded,
sum(case when NotFunded is null then 0 else NotFunded end) as NotFunded
from MyQuery group by year
輸出量
YEAR ISFUNDED NOTFUNDED
2003 3 4
2004 8 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.