我有两个桌子。一个带有日期,另一个带有礼物日期和礼物类型。第三张表显示了我想要达到的结果。 我想在表上显示一列产品日期为“结果”的列。结果应返回:
表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
答案 0 :(得分:1)
您可以使用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
我不知道表格的名称,因此您必须替换它们。