在SQL Server中使用CASE返回两个值

时间:2018-03-12 15:32:37

标签: sql sql-server

我有一个问题:这是问题,在我的表格中我有一些客户端采用这种格式:

id | year | Month | Amount 
---+------+-------+--------
1  | 2016 | 02    | 250.00
2  | 2013 | 08    | 350.00
3  | 2015 | 12    | 450.00
4  | 2016 | 02    | 750.00

在我的另一张表中,我有一个ClientStartDate列,格式为2015-12-15 00:00:00.000。因此,如果客户的开始日期是在该月的第15天,那么我需要有两条记录,第一条记录表示客户开始工作的日期,第二条记录表示同一客户,但下个月。它看起来应该是这样的,让我们说在2015-12-15开始id = 3的客户端,表应该是这样的:

id | year | Month | Amount 
---+------+-------+--------
1  | 2016 | 02    | 250.00
2  | 2013 | 08    | 350.00
3  | 2015 | 12    | 450.00
3  | 2016 | 01    | 150.00
4  | 2016 | 02    | 750.00

这是ClientStartDate来自的表格:

 id | Name   | ClientStartDate
 ---+--------+-------------------------
 1  | John   | 2016-02-01 00:00:00.000
 2  | Anna   | 2013-08-01 00:00:00.000
 3  | Mike   | 2015-12-15 00:00:00.000
 4  | Nicolas| 2016-02-04 00:00:00.000
 5  | Monika | 2013-11-15 00:00:00.000

这是FactTrans表,其中DateKey来自:

  id  | amount | DateKey
  ----+--------+----------
   1  | 208.67 | 20160201
   1  | 19.12  | 20160205
   2  | 55.42  | 20130820
   2  | 5.42   | 20130811
   4  | 23.98  | 20151121
   5  | 17.99  | 20140820

以下是我尝试的完整代码:

select 
    t1.ID, 
    left(cast(t1.datekey as varchar), 4) as Year,
    left(right(cast(t1.datekey as varchar), 4), 2) as Month, 
    sum(t1.amount) as SumAmount
from 
    .dbo.FactTrans t1
inner join 
    dbo.Client t2 on t2.clientid = t1.clientid 
where 
    (left(cast(t1.datekey as varchar), 4) = year(t2.clientstartdate) 
     and left(right(cast(t1.datekey as varchar), 4), 2) = month(t2.clientstartdate)) 
    or 
    (case
        when left(right(cast(t1.datekey as varchar), 4), 2)= 1 
           then 12
           else left(right(cast(t1.datekey as varchar), 4), 2) - 1 
     end = month(t2.ClientStartDate) 
    and 
               case
                  when
                     month(t2.ClientStartDate) = 12 
                  then
                    LEFT(cast(t1.datekey as varchar), 4) - 1 
                  else
                     LEFT(cast(t1.datekey as varchar), 4)
               end
                    = year(t2.ClientStartDate) 
               and 
               case
                when 
                day(t2.ClientStartDate) = 15 
                then
                month(t2.ClientStartDate)  + 1
                else
                month(t2.ClientStartDate) 
                end
                = left(cast(t1.datekey as varchar), 4)
        )
group by t1.clientid, LEFT(cast(t1.datekey as varchar), 4)  ,left(right(cast(t1.datekey as varchar), 4), 2) 
order by t1.clientID

此案例涵盖了当天= 15但月份=! 12,所以在这里我只需要在下个月而不是明年返回。所以我的问题是,有人可以帮我写一天= 15但月份= 12的情况,我需要在下一年和明年返回该客户。

这种情况是WHERE声明。

0 个答案:

没有答案