SQL Server CASE语句中的聚合选项

时间:2016-06-21 07:22:42

标签: sql sql-server sql-server-2008

我在#temp表中有以下数据:

Id  code       Fname       CompanyId    FieldName         Value
----------------------------------------------------------------
465 00133   JENN WILSON       1           ERA              1573
465 00133   JENN WILSON       1           ESHIFTALLOW      3658
465 00133   JENN WILSON       1           NETPAY          51560

我想做以下操作,即

  • One Row将添加两列,即ERA + ESHIFTALLOW
  • 其他行将减法&添加三列,即NETPAY - ERA + ESHIFTALLOW

我曾尝试在SQL Server中使用case语句。

这是查询

Select 
    Id, Code, Fname, CompanyID, Company, FieldNameNew,
    Sum(Value) Value 
Into 
    #temp2
from 
    (select 
         Id, Code, Fname, CompanyID, Company, Value,
         case 
            when FieldName in ('OT', 'EONCALLALLOW', 'ESHIFTALLOW', 'FOT', 'EUNIALLOW', 'ESECALLOW', 'ERA') 
               then 'OT+EONCALLALLOW+ESHIFTALLOW+FOT+EUNIALLOW+ESECALLOW+ERA'
            when FieldName in ('NETPAY') 
               then 'NETPAY-OT+EONCALLALLOW+ESHIFTALLOW+FOT+EUNIALLOW+ESECALLOW+ERA'      
            else FieldName 
         end, 
         FieldNameNew
     from 
         #temp) A
group by 
    Id, Code, Fname, CompanyID, Company, FieldNameNew

使用上述查询即可获得部分结果

Id  code          Fname  CompanyId   FieldNameNew                                                   Value
465 00133   JENN WILSON   1       NETPAY-OT+EONCALLALLOW+ESHIFTALLOW+FOT+EUNIALLOW+ESECALLOW+ERA    51560  //INCORRECT Actual value should be (51560-5231) = 46329
465 00133   JENN WILSON   1       OT+EONCALLALLOW+ESHIFTALLOW+FOT+EUNIALLOW+ESECALLOW+ERA           5231 //CORRECT

添加工作正常但在NETPAY中进行减法时却无法正常工作

  

NETPAY-OT + EONCALLALLOW + ESHIFTALLOW + FOT + EUNIALLOW + ESECALLOW + ERA   value = 51560 // INCORRECT实际值应为(51560-5231)= 46329

     

OT + EONCALLALLOW + ESHIFTALLOW + FOT + EUNIALLOW + ESECALLOW + ERA
  值= 5231 //正确

1 个答案:

答案 0 :(得分:2)

你有正确的逻辑,但错误的公式:

这是错误的方式

**NETPAY-OT+EONCALLALLOW+ESHIFTALLOW+FOT+EUNIALLOW+ESECALLOW+ERA**

您必须使用

**NETPAY-OT-EONCALLALLOW-ESHIFTALLOW-FOT-EUNIALLOW-ESECALLOW-ERA**

**NETPAY-(OT+EONCALLALLOW+ESHIFTALLOW+FOT+EUNIALLOW+ESECALLOW+ERA)**