2012-11-08 66 views
-1

是否有任何方法在PIVOTED列中擁有CASE SELECT語句?我的代碼如下在PIVOT中選擇

SELECT PName, [RN], [HA], [LVN], [MSW], [SC] 
FROM 
(
    Query 

) src 

    pivot 
    (
    max(Visits) 
    for Discipline in ([RN], [HA], [LVN], [MSW], [SC]) 
    ) piv 

我得到如下輸出

Pname  RN   HA   LVN  MSW  SC 
    AA  AG-2/W LO-1/W  NA-1/W  SK-2/W  NO-2/MON 
    AA  JL-2/W  NULL   NULL  NULL  NULL 

因爲曾經有分配到1 PN 2周的RN我想總結的結果只有1行,只有1選擇值顯示在RN列中,以便根據我的情況結果如下。

Pname  RN   HA   LVN  MSW  SC 
    AA  JL-2/W LO-1/W  NA-1/W  SK-2/W  NO-2/MON 

回答

0

你必須在旋轉之後移除數據,因爲[RN]本身受到MAX條件的影響,也就是說它本身就是一個樞軸柱。將其封裝在CTE中,正確應用RowNumber()函數和分區,然後將其過濾爲每個分區只有一行。

;WITH CTE AS (
    SELECT PName, [RN], [HA], [LVN], [MSW], [SC], 
      ROW_NUMBER() OVER (partition by PName order by [RN] ASC) RowNum 
    FROM 
    (
     Query 

    ) src 

     pivot 
     (
     max(Visits) 
     for Discipline in ([RN], [HA], [LVN], [MSW], [SC]) 
     ) piv 
) 
SELECT * 
    FROM CTE 
WHERE RowNum = 1; 
1

沒有看到完整的查詢內容,你應該能夠到ROW_NUMBER適用於內查詢,然後使用類似下面的WHERE條款:

SELECT PName, [RN], [HA], [LVN], [MSW], [SC] 
FROM 
(
    <yourQuery>, row_number() over(order by somefield) rn -- add a rownumber here 
) src 
pivot 
(
    max(Visits) 
    for Discipline in ([RN], [HA], [LVN], [MSW], [SC]) 
) piv 
where rn = 1 

如果您發佈完整的查詢,有可能是其他方式來做到這一點。

編輯,使用您的信息從以前的問題,您的查詢會是這樣:

select patname, [HA], [MSW], [RN] 
from 
(
    select patName, Disc, 
    sname+' '+schedule new_value, 
    row_number() over(partition by patname, disc order by disc) rowNum 
    from yourquery 
) src 
pivot 
(
    max(new_value) 
    for disc in ([HA], [MSW], [RN]) 
) piv 
where rownum = 1 

SQL Fiddle with Demo

或者你可以使用:

select * 
from 
(
    SELECT PName, [RN], [HA], [LVN], [MSW], [SC] , row_number() over(partition by PName order by PName) rn 
    FROM 
    (
     <yourQuery> 
    ) src 
    pivot 
    (
     max(Visits) 
     for Discipline in ([RN], [HA], [LVN], [MSW], [SC]) 
    ) piv 
) x 
where rn = 1 
+0

@ user1764540當你把'rownum'放在外部'where'結果是什麼?你爲什麼說它不起作用? – Taryn

+0

非常感謝你解決了我的問題 – user1764540