2016-12-13 158 views
0

我需要彙總在Microsoft SQL數據庫中水平擴展的數據。彙總水平SQL數據

+-------+---------+----------+---------+----------+---------+----------+---------+ 
| JOB | DATE | CC1_CODE | CC1_HRS | CC2_CODE | CC2_HRS | CC3_CODE | CC3_HRS | 
+-------+---------+----------+---------+----------+---------+----------+---------+ 
| A1234 | 12/1/16 | 0100  | 6  | 0300  | 2  | NULL  | 0  | 
+-------+---------+----------+---------+----------+---------+----------+---------+ 
| A1234 | 12/1/16 | 0200  | 8  | NULL  | 0  | NULL  | 0  | 
+-------+---------+----------+---------+----------+---------+----------+---------+  
| A1234 | 12/1/16 | 0100  | 4  | 0200  | 2  | 0300  | 2  | 
+-------+---------+----------+---------+----------+---------+----------+---------+ 

期望的結果將是 - 按作業和日化集團,然後總結了CODE所有的HRS。

+-------+---------+----------+---------+----------+---------+----------+---------+ 
| JOB | DATE | CC1_CODE | CC1_HRS | CC2_CODE | CC2_HRS | CC3_CODE | CC3_HRS | 
+-------+---------+----------+---------+----------+---------+----------+---------+ 
| A1234 | 12/1/16 | 0100  | 10  | 0200  | 10  | 0300  | 4  | 
+-------+---------+----------+---------+----------+---------+----------+---------+ 

注 - 列實際上從CC1到CC25。 CC_CODES可以存儲在任何CC_CODES字段中,它只取決於哪一個首先被輸入。

+3

純代碼編寫請求是題外話堆棧溢出 - 我們在這裏期待的問題涉及*具體*編程問題 - 但我們會很樂意幫助你自己寫!告訴我們[你試過的東西](http://stackoverflow.com/help/how-to-ask),以及你卡在哪裏。這也將幫助我們更好地回答你的問題。 –

+1

這是如何「聚合」? CC3_HRS列0 + 0 + 2 <> 4.該列發生了什麼? – WillardSolutions

回答

1

Yucky數據格式。一種方法是不轉發數據,然後重新聚合:

select job, date, code, sum(hrs) as hrs 
from t cross apply 
    (values (CC1_CODE, CC1_HRS), 
      (CC2_CODE, CC2_HRS), 
      . . . 
    ) c(code, hrs) 
group by job, date, code; 

我認爲沒有理由繼續嘗試處理該格式的數據。上面的數據在不同的行上返回。

但是,如果你真的必須,這裏是使用條件聚集的方法(和上面的查詢):

with a as (
     select job, date, code, sum(hrs) as hrs, 
      row_number() over (partition by job, date order by code) as seqnum 
     from t cross apply 
      (values (CC1_CODE, CC1_HRS), 
        (CC2_CODE, CC2_HRS), 
        . . . 
      ) c(code, hrs) 
     group by job, date, code 
    ) 
select job, date, 
     max(case when seqnum = 1 then code end) as code_01, 
     max(case when seqnum = 1 then hrs end) as hrs_01, 
     max(case when seqnum = 2 then code end) as code_02, 
     max(case when seqnum = 2 then hrs end) as hrs_02, 
     . . . 
from a 
group by job, date; 
+0

這很好。謝謝! –