如何联接相同的表但具有不同的条件以将多个结果作为列

时间:2019-06-19 09:20:57

标签: sql sql-server

所以我有一个这样的表(简化):

id|   Country_dsc | Year | Month |   Quantity  | Value |
1 |   Armenia     | 2019 |   2   |      4      |   2   |
2 |   Armenia     | 2019 |   3   |      6      |   4   |
3 |   Armenia     | 2018 |   1   |      6      |   5   |
4 |   Armenia     | 2018 |   2   |      3      |   3   |
5 |   Armenia     | 2018 |   3   |      7      |   5   |

我想得到这样的结果:

  Name        | YTD_Quantity_Y | YTD_Quantity_LY | YTD_Value_Y | YTD_Value_LY | 
  Armenia     |       10       |        16       |      6      |     13       |

,其中YTD_Quantity_Y是2019年所有数量的总和,而YTD_Quantity_LY是从年初到当前月份(在此示例中为3月)的2018年所有数量的总和。值的逻辑相同。

所以我尝试的是:

SELECT t1.Country_Dsc as Name,
        SUM(t1.Quantity) as YTD_Quantity_Y, -- January, February, March 2019
        SUM(t2.Quantity) as YTD_Quantity_LY -- January, February, March 2018
        SUM(t2.Value) as YTD_Value_Y  -- January, February, March 2019
        SUM(t2.Value) as YTD_Value_LY -- January, February, March 2018
FROM example_table t1
     LEFT JOIN example_table t2 on t1.Country_Dsc = t2.Country_Dsc
                                AND t1.Year = 2018 
                                AND t1.Month = t2.Month
WHERE t1.Year = 2019
      and t1.Month <= 3 -- in this case I want all data from January to March for 2019 and 2018 
GROUP BY t1.Country_Dsc

问题是,自2019年以来没有1月份的记录,我没有在 YTD_Quantity_LY 中获得2018年1月的数量。

如果我从2018年开始并在2019年加入,那么它会起作用,但有时我遇到的情况是在2018年我没有一个月的记录,因此不会在2019年显示( YTD_Quantity_Y )。

是否可以在不使用每年查询的情况下获得我想要的结果?

1 个答案:

答案 0 :(得分:1)

请尝试以下查询:

declare @tbl table (id int, Country_dsc varchar(10), [Year] int, [Month] int, Quantity int, [Value] int );
insert into @tbl values
(1 , 'Armenia' , 2019 , 2 , 4 , 2 ),
(2 , 'Armenia' , 2019 , 3 , 6 , 4 ),
(3 , 'Armenia' , 2018 , 1 , 6 , 5 ),
(4 , 'Armenia' , 2018 , 2 , 3 , 3 ),
(5 , 'Armenia' , 2018 , 3 , 7 , 5 )

select Country_dsc [Name],
       sum(case when year = 2019 then quantity else 0 end) YTD_Quantity_Y ,
       sum(case when year = 2018 then quantity else 0 end) YTD_Quantity_LY ,
       sum(case when year = 2019 then Value else 0 end) YTD_Value_Y ,
       sum(case when year = 2018 then Value else 0 end) YTD_Value_LY 
from @tbl
group by Country_dsc