2015-01-06 35 views
0

如何將兩行合併到單行中?如何根據SQL Server 2008中的條件添加2行的總和

現在這是什麼我得到...

LeaveTypeId LeaveTypeFName  day 
--------------------------------------- 
1   Casual Leave   9.0 
3   SickLeave   3.0 
10   Festival    4.0 
11   LOP     15.0 
14   National Holiday  4.0 
18   P-SickLeave   1.0 
19   P-Casual Leave  3.0 

但我預計產量

LeaveTypeId LeaveTypeFName   day 
-------------------------------------------- 
1   Casual Leave(All)  12.0 
3   SickLeave(All)   4.0 
10   Festival     4.0 
11   LOP      15.0 
14   National Holiday   4.0 

這是我的SQL查詢

select 
    b.LeaveTypeId,LeaveTypeFName, 
    SUM(case when LeaveStatus = 'FullDay' 
       then DATEDIFF(day, FromDate, ToDate) + 1 
       else 0.5 
     end) as 'day' 
from 
    LeaveEntries a 
join 
    LeaveTypes b on a.LeaveTypeId = b.LeaveTypeId 
where 
    EmployeeId = '3862' 
group by 
    LeaveTypeFName, b.LeaveTypeId 

這是我LeaveEntries表

LeaveEntryId LeaveTypeId LeaveStatus EmployeeId FromDate   ToDate   
    19    3   FullDay  3484  2013-02-06  2013-02-09 
    21    1   HalfDay  3484  2013-03-07  2013-03-07 
+0

您最好顯示錶架構和示例數據。 – dario

回答

0

使用Case Statement來做到這一點。

SELECT CASE 
     WHEN LeaveTypeFName LIKE '%Casual Leave%' THEN 'Casual Leave(All)' 
     WHEN LeaveTypeFName LIKE '%SickLeave%' THEN 'SickLeave (All)' 
     WHEN LeaveTypeFName LIKE '%Festival%' THEN 'Festival' 
     WHEN LeaveTypeFName LIKE '%LOP%' THEN 'LOP' 
     WHEN LeaveTypeFName LIKE '%National Holiday%' THEN 'National Holiday' 
     END LeaveTypeFName, 
     Sum([day]) [day] 
FROM result 
GROUP BY CASE 
      WHEN LeaveTypeFName LIKE '%Casual Leave%' THEN 'Casual Leave(All)' 
      WHEN LeaveTypeFName LIKE '%SickLeave%' THEN 'SickLeave (All)' 
      WHEN LeaveTypeFName LIKE '%Festival%' THEN 'Festival' 
      WHEN LeaveTypeFName LIKE '%LOP%' THEN 'LOP' 
      WHEN LeaveTypeFName LIKE '%National Holiday%' THEN 'National Holiday' 
      END 
+0

我對此表示懷疑,因爲根據預期的輸出用戶希望只通過LeaveTypeFName組,而不是ID。 – AK47

+1

@ AK47 - 是的你是對的,但是,我不確定他在結果中得到了那些'LeaveTypeId'。 –

1

我沒試過,

的想法只是把你目前的結果,因爲它是,剛剛從結果LeaveTypeFName &刪除「P-」然後再組。希望這項工作!

;With CTE as 
(
    select 
     b.LeaveTypeId 
     ,Case When b.LeaveTypeId in(18,19) 
       Then Replace(LeaveTypeFName,'P-','') 
       Else LeaveTypeFName 
     End as LeaveTypeFName 
     ,SUM(case when LeaveStatus = 'FullDay' 
       Then DATEDIFF(day, FromDate, ToDate) + 1 
       Else 0.5 
      end) as 'day' 
    from LeaveEntries a 
    join LeaveTypes b on a.LeaveTypeId = b.LeaveTypeId 
    where EmployeeId = '3862' 
    group by LeaveTypeFName, b.LeaveTypeId 
) 
Select max(LeaveTypeId) as LeaveTypeId 
     ,LeaveTypeFName 
     ,Sum(day) 
    from CTE 
group by LeaveTypeFName 
相關問題