sql-server - 如何根据日期字段分配值?
问题描述
我有两张桌子。一个带有日期,另一个带有礼物日期和礼物类型。第三个表显示了我希望达到的结果。我想在表格上显示一个名为“结果”的产品日期列。结果应返回:
- 如果产品日期之前没有礼物日期,则“不是捐赠者”。
- '产品捐赠者' 如果在日期之前只有一种礼品类型的产品。
- '多个产品捐赠者'如果在日期之前有多种产品礼物类型(但不能有“其他”礼物类型)。
- 如果有“其他”礼品类型,则为“其他捐赠者”,无论之前有多少产品。
表格1
Donor Date
Steve 2/1/2020
Steve 3/1/2020
Steve 4/1/2020
Steve 5/1/2020
Steve 6/1/2020
Steve 7/1/2020
Steve 9/1/2020
Steve 10/1/2020
Bill 2/1/2020
Bill 3/1/2020
Bill 4/1/2020
Bill 5/1/2020
Bill 6/1/2020
Bill 7/1/2020
Bill 8/1/2020
表 2
Donor Gift Date Gift Type
Steve 8/15/2020 Product
Steve 9/15/2020 Product
Bill 5/15/2020 Product
Bill 6/15/2020 Other
Bill 7/15/2020 Product
预期结果
Donor Date Results
Steve 2/1/2020 Not A Donor
Steve 3/1/2020 Not A Donor
Steve 4/1/2020 Not A Donor
Steve 5/1/2020 Not A Donor
Steve 6/1/2020 Not A Donor
Steve 7/1/2020 Not A Donor
Steve 9/1/2020 Products Donor
Steve 10/1/2020 Multiple Products Donor
Bill 2/1/2020 Not A Donor
Bill 3/1/2020 Not A Donor
Bill 4/1/2020 Not A Donor
Bill 5/1/2020 Not A Donor
Bill 6/1/2020 Products Donor
Bill 7/1/2020 Other Donor
Bill 8/1/2020 Other Donor
解决方案
您可以使用 Case 语句来考虑每个可能的输出:
select T.Donor,
T.Date,
Results = Case when not exists (Select top 1 1 From table2 where Donor = T.Donor and [Gift Date] < T.[Date]) then 'Not A Donor'
when exists (Select top 1 1 From table2 where Donor = T.Donor and [Gift Date] < T.[Date] and [Gift Type] = 'Other') then 'Other Donor'
when (Select count(1) From table2 where Donor = T.Donor and [Gift Date] < T.[Date] and [Gift Type] = 'Product') = 1 then 'Products Donor'
when (Select count(1) From table2 where Donor = T.Donor and [Gift Date] < T.[Date] and [Gift Type] = 'Product') > 1 then 'Multiple Products Donor'
end
from table1 T
我不知道您的表的名称,因此您必须替换它们。
推荐阅读
- javascript - XMLHttpRequest 到另一个具有 cookie 持久性的子域?
- apache - 如何使用 htaccess 更改我的站点 URL?
- php - 开发(本地主机)和托管服务之间的 PHP 会话差异
- javascript - 在 React.js 项目中启动本地主机服务器时出现 npm start 错误
- c# - HangFire 从服务迁移
- python - function() 缺少 4 个必需的位置参数
- latex - Knit RMarkdown 报错,pdfLaTeX 编译失败
- javascript - 尝试在双数组中填充任何情况 - javascript
- reactjs - 如何在 JSX 中包含逻辑来转换对象?
- tar - tar 命令因“懦弱地拒绝创建空存档”而失败