首页 > 解决方案 > 如何根据日期字段分配值?

问题描述

我有两张桌子。一个带有日期,另一个带有礼物日期和礼物类型。第三个表显示了我希望达到的结果。我想在表格上显示一个名为“结果”的产品日期列。结果应返回:

表格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

标签: sql-server

解决方案


您可以使用 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

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


推荐阅读