SQL SUM语句返回不同的结果

时间:2013-06-17 18:49:19

标签: sql sql-server tsql crosstab

有人可以解释为什么下面的两个select语句结果不同! 我知道第一个语句是正确的(使用CASE),但我不明白为什么第二个语句是错误的。

CREATE TABLE #sales
(
YearSold int,
Quarter char(2),
Amount money
)
GO

INSERT INTO #sales (YearSold, Quarter, Amount) values (2003, 'Q1', 1)
INSERT INTO #sales (YearSold, Quarter, Amount) values (2003, 'Q2', 2)
INSERT INTO #sales (YearSold, Quarter, Amount) values (2003, 'Q3', 3)
INSERT INTO #sales (YearSold, Quarter, Amount) values (2003, 'Q4', 4)
INSERT INTO #sales (YearSold, Quarter, Amount) values (2004, 'Q1', 5)
INSERT INTO #sales (YearSold, Quarter, Amount) values (2004, 'Q2', 6)
INSERT INTO #sales (YearSold, Quarter, Amount) values (2004, 'Q3', 7)
INSERT INTO #sales (YearSold, Quarter, Amount) values (2004, 'Q4', 8)
INSERT INTO #sales (YearSold, Quarter, Amount) values (2005, 'Q1', 9)
INSERT INTO #sales (YearSold, Quarter, Amount) values (2005, 'Q2', 10)
INSERT INTO #sales (YearSold, Quarter, Amount) values (2005, 'Q3', 0)
INSERT INTO #sales (YearSold, Quarter, Amount) values (2005, 'Q4', 0)

GO

SELECT YearSold,
 SUM(CASE Quarter WHEN 'Q1' THEN Amount ELSE 0 END) AS Q1,
 SUM(CASE Quarter WHEN 'Q2' THEN Amount ELSE 0 END) AS Q2,
 SUM(CASE Quarter WHEN 'Q3' THEN Amount ELSE 0 END) AS Q3,
 SUM(CASE Quarter WHEN 'Q4' THEN Amount ELSE 0 END) AS Q4
FROM #sales
GROUP BY YearSold

SELECT t.YearSold, SUM(a.Amount) AS Q1, SUM(b.Amount) AS Q2, SUM(c.Amount) AS Q3, SUM(d.Amount) AS Q4
FROM #sales t
LEFT JOIN #sales a ON t.YearSold = a.YearSold AND a.Quarter='Q1'
LEFT JOIN (select * from #sales where Quarter='Q2') b ON t.YearSold = b.YearSold 
LEFT JOIN (select * from #sales where Quarter='Q3') c ON t.YearSold = c.YearSold 
LEFT JOIN (select * from #sales where Quarter='Q4') d ON t.YearSold = d.YearSold
GROUP BY t.YearSold

--select * from  #sales

DROP TABLE #sales

注意:使用SQL Server 2008 Express

1 个答案:

答案 0 :(得分:4)

left join返回左侧表格中每一行的右侧表格中的每个匹配行。

要查看会发生什么,请从第二个查询中删除group by

SELECT *
FROM #sales t
LEFT JOIN #sales a ON t.YearSold = a.YearSold AND a.Quarter='Q1'
LEFT JOIN (select * from #sales where Quarter='Q2') b ON t.YearSold = b.YearSold 
LEFT JOIN (select * from #sales where Quarter='Q3') c ON t.YearSold = c.YearSold 
LEFT JOIN (select * from #sales where Quarter='Q4') d ON t.YearSold = d.YearSold

你会发现每年有四行。那是因为from #sales每年会给你四行。最终结果是group by计算了四次。