简体   繁体   English

如何展平SQL查询的结果?

[英]How do I flatten results from my SQL Query?

I have a query that returns the following table: 我有一个查询,返回下表:

Year    IsFunded     NotFunded
2003    Null         4
2003    3            Null
2004    Null         2
2004    8            Null

So I need: 所以我需要:

SELECT Year, IsFunded, NotFunded
FROM
(
    --myQuery that returns unflattened results
)

I just need one row for each year. 每年只需要一行。 like: 喜欢:

Year    IsFunded     NotFunded
2003    3            4
2004    8            2

Use GROUP BY and MAX : 使用GROUP BYMAX

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;

I would replace null with 0 while sum and just add group by year, like below 我会在总和时将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

Output 输出量

        YEAR ISFUNDED  NOTFUNDED
        2003     3         4
        2004     8         2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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