在SQL中标记

时间:2018-09-27 09:42:28

标签: tsql

我正在基于sql中的条件标记用户。如何在sql中完成?

例如:在下表中,如果任何ID的date2> = date1,则应将其标记为“ A”,否则标记为“ B”。但是,如果date2 = date1的情况也应标记为“ B”。如何在SQL中实现?

预期结果如结果列所示

ID  Date1           Date2            Result
100 15 March 2018   15 April 2018    B 
100 15 March 2018   15 January 2018  B
101 15 March 2018   15 April 2018    B
101 15 March 2018   20 June 2018     B
101 15 March 2018   17 January 2018  B
101 15 March 2018   14 July 2018     B
105 15 March 2018   25 May 2018      A

1 个答案:

答案 0 :(得分:0)

您正在寻找一个简单的case表达式-它等效于if...then...else块的SQL-与窗口函数结合以找到min Date1和{ {1}}值用于“整个ID”比较。

您的情况如下:

Date2

输出:

declare @t table(ID int, Date1 date, Date2 date);
insert into @t values
 (100, '20180501',   '20180415')
,(100, '20180501',   '20180115')
,(101, '20180501',   '20180415')
,(101, '20180501',   '20180620')
,(101, '20180501',   '20180117')
,(101, '20180501',   '20180714')
,(105, '20180501',   '20180525');

select ID
      ,Date1
      ,Date2
      ,case when min(Date2) over (partition by ID) < min(Date1) over (partition by ID)
              then 'B'
              else case when Date2 >= Date1
                          then 'A'
                          else 'B'
                          end
              end as Result
from @t;