将记录移动到单行

时间:2013-12-17 07:18:36

标签: sql sql-server case

我正在尝试将SQL记录转换为单行,因此可以在我加入表格的其他查询中轻松使用它。John example worked with me.

我的表看起来像这样。

EmpID | DeductionType | HoursDeduction | DeductionAmount | Year | Month
ABC   | F             |  4             | $2.00           | 2013 | 10
ABC   | H             |  2             | $1.50           | 2013 | 10

我的情况我必须根据另一个字段选择两个字段。

SELECT empid, 
       year1    AS [Year], 
       month1   AS [Month], 
       Max(CASE deductiontype 
             WHEN 'F' THEN hoursdeduction 
             ELSE 0 
           END) FullDeductionHours, 
       Max(CASE deductiontype 
             WHEN 'F' THEN deductionamount 
             ELSE 0 
           END) FullDeductionAmount, 
       Max(CASE deductiontype 
             WHEN 'H' THEN hoursdeduction 
             ELSE 0 
           END) HalfDeductionHours, 
       Max(CASE deductiontype 
             WHEN 'H' THEN deductionamount 
             ELSE 0 
           END) HalfHourDeductionAmount 
FROM   mydeductiontable 
GROUP  BY empid, 
          year1, 
      month1 

我只想知道它是否有效且不会减慢我的存储过程,我试图找到扣减时间并将其用于计算工资核算数据。反正我们可以让查询更聪明吗?

0 个答案:

没有答案