如何基于日期字段分配值?

时间:2020-08-21 17:15:11

标签: 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

1 个答案:

答案 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

我不知道表格的名称,因此您必须替换它们。