繁体   English   中英

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

[英]How to join the same table but with different criteria to have multiple result as column

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

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 )。

不用每年查询就可以得到我想要的结果吗?

请尝试以下查询:

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

暂无
暂无

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

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