我試圖創建一個數據透視表來轉換值的範圍。我使用這個總和技巧,但我最近了解到了pivot操作符,並且我試圖將數據轉換爲數據透視表,因爲代碼可能更容易維護。 (我已經改名爲我的表模糊的數據位)轉軸列的值是範圍
select consultation_id,
sum(case when current_status_id in (3,4,5,9,10,16,17,18,24,25,26) then 1 else 0 end) [Phase1],
sum(case when current_status_id in (4,9,10,16,17,18) then 1 else 0 end) [Phase2],
sum(case when current_status_id in (10,16,17,18) then 1 else 0 end) [Phase3],
sum(case when current_status_id = 24 then 1 else 0 end) [Rejected],
sum(case when current_status_id in (17,18) then 1 else 0 end) [Complete]
from subject with (NOLOCK,NOWAIT)
where ACTIVE_IND = 1
group by consultation_id
任何人有如何做轉換有何建議?
編輯: 基本上,我創建了多少個主題的總和,使它成爲我們磋商的一個階段。這是爲lucene索引構建的聚合,以便我們的用戶可以搜索特定的數據。 這裏是原始表格數據的一個例子,什麼輸出可能看起來像::
select consultation_id,
sum(case when current_status_id in (3,4,5,9,10,16,17,18,24,25,26) then 1 else 0 end) [Phase1],
sum(case when current_status_id in (4,9,10,16,17,18) then 1 else 0 end) [Phase2],
sum(case when current_status_id in (10,16,17,18) then 1 else 0 end) [Phase3],
sum(case when current_status_id = 24 then 1 else 0 end) [Rejected],
sum(case when current_status_id in (17,18) then 1 else 0 end) [Complete]
from (values(1588054,11928257,3,1),
(1588054,11928256,10,1),
(1588054,11928255,10,1),
(1588054,11928254,4,1),
(1588052,11928233,2,1),
(1588052,11928232,3,0),
(1588052,11928231,10,1),
(1588052,11928230,18,1),
(1588052,11928229,24,1),
(1588052,11928228,24,1)) subject (consultation_id,subject_id,current_status_id,active_ind)
where ACTIVE_IND = 1
group by consultation_id
你可以發佈一些樣本數據,然後預期的結果?從數據的起點將其轉換爲「PIVOT」可能更容易。或者甚至用示例數據創建一個[sql小提琴](http://sqlfiddle.com/)。 – Taryn
我已經添加了一個查詢,用相關的列和一些示例數據替換帶有值表的實際表。 –