我正在使用 Server 2012 中的以下架构和查询创建年度捐赠报告:
CREATE TABLE Donation
(
HouseholdID INT,
HouseholdName VARCHAR(150),
[Donation] REAL,
DateOrdered DATE
);
INSERT Donation VALUES
(1,'The Smiths',50,'2011-01-01'),
(1,'The Smiths',75,'2012-02-02'),
(2,'The Wilsons',10,'2011-03-01'),
(2,'The Wilsons',60,'2011-07-01'),
(3,'The Kellys',500,'2012-06-01');
--Params
DECLARE @RunYear INT=2012
DECLARE @PriorYear INT=@RunYear-1
SELECT
[HouseholdID],[HouseholdName],YEAR(DateOrdered) [Year], MAX(Donation) [MaxGift], SUM(Donation) [TotalDonated]
FROM
Donation
WHERE
YEAR([DateOrdered]) IN (@RunYear,@PriorYear)
GROUP BY HouseholdID, [HouseholdName], YEAR(DateOrdered)
ORDER BY HouseholdID, YEAR(DateOrdered)
我想添加一个BIT
类似于 [DonatedInPriorYearOnly] 的列,仅当家庭在前一年(2011 年)有捐款但在运行年(2012 年)没有捐款时才为 1。
如何实现?