SQL QUERY,2 个汇总值(列),分组依据相同,只是年份不同

SQL QUERY, 2 Summed Values (Columns) with same grouped by except that years are different

SQL 这里是新手。我想向任何人寻求帮助,以获取基于多个组的 2 个值的总和,但唯一的区别是年份。请在下面查看我的示例:

数据库:

=============================================
NAME     COUNTRY      CITY     YEAR     VALUE
=============================================
Alpha    Philippines  Manila   2015     5
Beta     Philippines  Cebu     2015     3
Alpha    Philippines  Cebu     2015     4
Alpha    Philippines  Cebu     2015     1
Alpha    Philippines  Manila   2015     3
Alpha    Philippines  Manila   2015     5
Alpha    Philippines  Manila   2014     10
Beta     Philippines  Cebu     2014     1
Alpha    Philippines  Cebu     2014     15
=============================================

结果:

============================================================
NAME     COUNTRY      CITY     VALUE (2014)     VALUE (2015)
============================================================
Alpha    Philippines  Cebu     15               5
Alpha    Philippines  Manila   10               13
Beta     Philippines  Cebu     1                3
============================================================

并非所有列都来自同一个 table。说: 1) 姓名、国家和城市 - dbo.Product 2) 年 - dbo.Calendar 3) 值 - dbo.SellThru ***关键值为CompanyKey

希望我解释正确,提前谢谢你^^

您可以使用条件将值汇总到不同的列中,以便每列仅获取当年的行。

类似这样的东西(我实际上没有 运行 所以可能语法有一些小错误):

SELECT name, country, city,
   SUM(CASE year WHEN 2014 THEN value ELSE 0 END) as Value2014,
   SUM(CASE year WHEN 2015 THEN value ELSE 0 END) as Value2015
FROM <table-name-here> 
GROUP by name, country, city

您可以使用 PIVOT table 运算符:

SELECT 
  Name, 
  Country, 
  City, 
  [2015] AS 'Value(2015)', 
  [2014] AS 'Value(2014)'
FROM table1 AS t1
PIVOT
(
   MAX([Value])
  FOR [Year] IN([2015], [2014])
) AS p;

在您的情况下,不要使用 FROM table1 AS t1,而是使用从三个 table 中选择五个列 NAME COUNTRY CITY YEAR VALUE 的子查询。


更新

SELECT
  ..
  ..
  ,[2014] AS 'Value(2014)' 
  ,[2015] AS 'Value(2015)' 
FROM
(
   -- Here you should put the subquery
   SELECT
     dmCal.sFiscalYYYY
     ,ftSel.nNetUnits
     ..
     ..
     -- Select other columns here.
   FROM ftSellthru ftSel (NOLOCK) 
   INNER JOIN dmCalendar dmCal (NOLOCK) 
           on ftSel.iTransactionDateKey = dmCal.iCalendarKey 
) AS t
PIVOT 
(
   MAX(nNetUnits) -- Only nNetUnits without the alias ftSel as it is not recognized here
   FOR sFiscalYYYY IN([2015], [2014]) 
) AS p;