选择Case FROM Union

时间:2017-10-13 10:47:40

标签: sql sql-server select case union

为了报告和创建报告(MS SQL SERVER 2014),它将比较上一天,上周当天和上个月当天的交易数量和金额,我需要一些像这样的查询,这是不行的:

Select 
   Acquirer = case when Date = @Day then a.Acquirer
                   when Date = @LastWeekDay then b.Acquirer
                   when Date = @LastMonthDay then c.Acquirer
              end
,  RC =       case when Date = @Day then a.RC
                   when Date = @LastWeekDay then b.RC
                   when Date = @LastMonthDay then c.RC
              end
, Desc =      case when Date = @Day then a.Desc
                   when Date = @LastWeekDay then b.Desc
                   when Date = @LastMonthDay then c.Desc
              end
, Day_Tr_Count =  case when Date = @Day then a.Count end
, LWD_Tr_Count =  case when Date = @LastWeekDay then b.Count end
, LMD_Tr_Count =  case when Date = @LastMonthDay then c.Count end
, Day_Tr_Amount =  case when Date = @Day then a.Amount end
, LWD_Tr_Amount =  case when Date = @LastWeekDay then b.Amount end
, LMD_Tr_Amount =  case when Date = @LastMonthDay then c.Amount end

from
  ( select * from T1
     union
    select * from T2
     union
    select * from T3) x
group by Acquirer,RC,Desc

所有3个表都具有相同的结构:

T1,T2,T3(acquirer,RC,Desc,Count,Amount,Date).

报告应该是:

result_table(Acquirer,RC,Desc,Daily_Count,Last_Week_Day_Count,Last_Month_Count,Daily_Amount,Last_Week_Day_Amount,Last_Month_Day_Amount)

1 个答案:

答案 0 :(得分:0)

嗯。您有一个没有group by的聚合查询。也许:

Select v.Acquirer, v.RC, v.Desc,
       Day_Tr_Count =  sum(case when Date = @Day then a.Count end),
       LWD_Tr_Count =  sum(case when Date = @LastWeekDay then b.Count end),
       LMD_Tr_Count =  sum(case when Date = @LastMonthDay then c.Count end),
       Day_Tr_Amount =  sum(case when Date = @Day then a.Amount end
       LWD_Tr_Amount =  sum(case when Date = @LastWeekDay then b.Amount end),
       LMD_Tr_Amount =  sum(case when Date = @LastMonthDay then c.Amount end)

from (select * from T1
      union all
      select * from T2
      union all
      select * from T3
     ) x cross apply
     (values (case when Date = @Day then a.Acquirer
                   when Date = @LastWeekDay then b.Acquirer
                   when Date = @LastMonthDay then c.Acquirer
              end,
              case when Date = @Day then a.RC
                   when Date = @LastWeekDay then b.RC
                   when Date = @LastMonthDay then c.RC
              end,
              case when Date = @Day then a.Desc
                   when Date = @LastWeekDay then b.Desc
                   when Date = @LastMonthDay then c.Desc
              end
             ) v (Acquirer, RC, Desc)
group by v.Acquirer, v.RC, v.Desc;

注意:desc是列(或其他任何内容)的错误名称。它是一个SQL关键字(想想order by)。