gpt4 book ai didi

sql - 如何显示捐赠是否发生在前一年而不是当前?

转载 作者:行者123 更新时间:2023-12-02 08:43:06 25 4
gpt4 key购买 nike

我正在 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)

我想添加一个像 [DonatedInPriorYearOnly] 这样的 BIT 列,只有当该家庭在上一年(2011 年)有捐款但在运行年(2012 年)没有捐款时,该列才会为 1 .

如何实现?

最佳答案

根据您的 SQLServer 版本,您可以包装摘要查询(在子查询或 CTE 中)并使用 LAG .如果 HouseholdID 和 Year 与 LAG HouseholdID 和(Year - 1)不匹配,则上一年没有捐赠。

大致像这样(未经测试):

SELECT [HouseholdID], [HouseholdName], [Year], [MaxGift], [TotalDonated]
,CASE WHEN YEAR = previous_year +1 THEN 1 ELSE 0 END AS DonatedPreviousYear

FROM ( SELECT [HouseholdID], [HouseholdName], [Year], [MaxGift], [TotalDonated]
,LAG(Year, 1, 0) OVER (PARTITION BY HouseholdID ORDER BY Year) AS previous_year

FROM ( SELECT [HouseholdID],[HouseholdName],YEAR(DateOrdered) [Year], MAX(Donation) [MaxGift], SUM(Donation) [TotalDonated]
FROM Donation
WHERE [DateOrdered] BETWEEN @StartDt AND @EndDt
GROUP BY HouseholdID, [HouseholdName], YEAR(DateOrdered)
ORDER BY HouseholdID, YEAR(DateOrdered)
)
)

关于sql - 如何显示捐赠是否发生在前一年而不是当前?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14866614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com