这有效:
SELECT Date, Prop_Code, MBA_Account, SUM([12.31.2017_YTD]) AS Q1
FROM [2017DB]
WHERE (Date = '2017-06-30')
GROUP BY Date, Prop_Code, MBA_Account
我试图输出select语句和相同select语句之间的差异,只有第二个select语句的日期为03-31。
我相信这可以通过子查询来实现,但我是初学者并且在构建它时遇到一些困难。
这不起作用:
Select(
SELECT Date, Prop_Code, MBA_Account, SUM([12.31.2017_YTD]) AS Q1
FROM [2017DB]
WHERE (Date = '2017-06-30'))
-
SELECT Date, Prop_Code, MBA_Account, SUM([12.31.2017_YTD]) AS Q1
FROM [2017DB]
WHERE (Date = '2017-03-31'))
GROUP BY Date, Prop_Code, MBA_Account
Data > Date Prop_Code MBA_Account 12.31.2017_YTD
3/31/2017 Balt Administrative 100
3/31/2017 Balt Administrative 100
6/30/2017 Balt Administrative 500
6/30/2017 Balt Administrative 500
Desired result > Prop_Code MBA_Account Q2
Balt Administrative 800
期望的结果是计算: sum(6/30 YTD记录) - 总和(3/31 YTD记录)
最终有效的代码是戈登建议的一个版本:
SELECT Prop_Code, MBA_Account,
SUM(CASE WHEN DATE = '2017-09-30' THEN [12.31.2017_YTD] END) -
SUM(CASE WHEN DATE = '2017-06-30' THEN [12.31.2017_YTD] END) AS 'Q3'
FROM [2017DB].[dbo].[2017DB]
Group by Prop_Code, MBA_Account
答案 0 :(得分:0)
您可以使用条件聚合:
SELECT Date, Prop_Code, MBA_Account,
SUM(CASE WHEN DATE = '2017-03-31' THEN [12.31.2017_YTD] END) AS Q1_1,
SUM(CASE WHEN DATE = '2017-06-30' THEN [12.31.2017_YTD] END)) AS Q1_2
FROM [2017DB]
WHERE Date IN ('2017-06-30', '2017-03-31')
GROUP BY Date, Prop_Code, MBA_Account;
差异只是SUM()
表达式的差异。