如何制作这个SQL SELECT?

时间:2015-06-25 15:34:39

标签: sql join sql-server-2012

我无法弄清楚如何为每个工厂选择这两年的比较。

SELECT PlantName, SUM(Amount) AS Amount_Harvested_2014 
FROM Harvest
WHERE year=2014
GROUP BY PlantName

在所需的输出中,行应如下所示:

PlantName  2014Amount  2015Amount  2015-2014Amount

表格:

CREATE TABLE Harvest(
 harvest_id int PRIMARY KEY IDENTITY(1,1),
 PlantName nvarchar(20) NOT NULL FOREIGN KEY REFERENCES Plants(PlantName),
 Amount int NOT NULL,
 year int,
 harvester_id int NOT NULL FOREIGN KEY REFERENCES Workers(Worker_ID)
)

表格的示例内容:

harvest_id  PlantName   Amount  year    harvester_id
1           Rose        32      2015    2
2           Rose        12      2015    5

2 个答案:

答案 0 :(得分:1)

这样做的一个简单方法(可能不是最好的)是使用这样的条件聚合:

select 
    PlantName
    ,sum(case when year=2014 then Amount else 0 end) as "2014amount"
    ,sum(case when year=2015 then Amount else 0 end) as "2015amount"
    ,sum(case when year=2015 then Amount else 0 end) - sum(case when year=2014 then Amount else 0 end) as "2015-2014Amount"
from harvest
group by plantname

答案 1 :(得分:0)

执行此操作的好方法是使用SQL Server中的pivot选项:

select *, [2015] -[2014] as '2015-1014'
from 
(
  select PlantName, year, Amount
  from Harvest
) src
pivot
(
  sum(Amount)
  for year in ([2014], [2015])
) piv;

将提供以下输出:

PlantName 2014 2015 2015-1014

Apple 2 15 13

罗斯11 44​​ 33

如果添加更多年历史,这也可以更轻松地进行更新。