SQL CASE语句做多个thens

时间:2014-06-27 13:34:11

标签: sql case teradata

我正在尝试简化一个基于case语句创建唯一变量的SQL程序。因此,例如,假设我有一个如下数据集:

Salesperson   Invoice  ItemCount   Sales   Type
Joe           1111       100      500.00   internet
Joe           2222       50       200.00   internet
Joe           3333       200      750.00   store
Cthulhu       4444       10       50.00    internet
Cthulhu       5555       20       100.00   internet

我想最终得到类似的东西:

Salesperson  InternetItems  InternetSales  StoreItems  StoreSales  TotalItems  TotalSales
Joe             150              700.00      200          750.00     350          1450.00
Cthulhu          30              150.00      .            .          30           150.00

所以现在我有类似的东西:

select 
  salesperson, 
  case when Type='internet' then ItemCount else .
    end as InternetItems,
  case when Type='internet' then Sales else .
    end as InternetSales,

....more code....

  sum(ItemCount) as TotalItems,
  sum(Sales) as TotalSales,
 group by 1,2,3....

我希望能够通过以下方式来缩小这个:

select 
  salesperson, 
  case when Type='internet' then InternetItems=ItemCount and InternetSales=Sales
    else InternetItems=. and InternetSales=.

在涉及多个变量的创建时,有没有办法做到这一点?

另外,sum语句如何工作?是吗:

calculated(sum(InternetItems)) as InternetItems

谢谢,Pyll

2 个答案:

答案 0 :(得分:2)

无法从单个CASE中获取多个结果/列,但它主要通过剪切和粘贴以及修改来创建不同的列:

select 
  salesperson, 
  sum(case when Type='internet' then ItemCount else 0 end) as InternetItems,
  sum(case when Type='internet' then Sales     else 0 end) as InternetSales,
  sum(case when Type='store'    then ItemCount else 0 end) as StoreItems,
  sum(case when Type='store'    then Sales     else 0 end) as StoreSales,
  sum(ItemCount) as TotalItems,
  sum(Sales) as TotalSales
...
 group by 1

答案 1 :(得分:1)

我不完全确定我理解,但我认为您想要构建两个条件语句然后对每个语句进行求和?如果有意义,你就不能有一个产生两个输出列的case语句。

如果要聚合每个,只需将整个案例陈述相加,如下所示:

SUM (CASE when Type='internet' then ItemCount else ... end) as InternetItems ,...