這是不完全清楚你想達到什麼樣的,但你可以實現的row_number()
使用,以防止pname
在附加行顯示:
select case when rownum = 1 then pname else '' end pname,
[RN], [LVN], [HA], [MSW], [SC]
from
(
select pname, disc, value,
ROW_NUMBER() over(partition by disc order by disc) rownum
from temp
) src
pivot
(
max(value)
for disc in ([RN], [LVN], [HA], [MSW], [SC])
) piv
見SQL Fiddle with demo
結果:
| PNAME | RN | LVN | HA | MSW | SC |
----------------------------------------------------
| AA | AG-1W | SS-1M | LO-2W | PA-1W | SK-1M |
| | JL-1W | TD-1M | (null) | (null) | (null) |
Ť他使用row_number()
的值來決定是否應該顯示pname
。它只會顯示rownum=1
的值,否則將會爲空。
如果你想在一個行的數據,你可以使用類似於下面的內容:
;with cte as
(
select pname, disc, value,
ROW_NUMBER() over(partition by disc order by disc) rownum
from temp
),
piv as
(
select *
from cte
pivot
(
max(value)
for disc in ([RN], [LVN], [HA], [MSW], [SC])
) piv
)
select pname,
STUFF((SELECT distinct ', ' + [RN]
from piv p2
where p1.pname = p2.pname
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'') RN,
STUFF((SELECT distinct ', ' + [LVN]
from piv p2
where p1.pname = p2.pname
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'') LVN,
STUFF((SELECT distinct ', ' + [HA]
from piv p2
where p1.pname = p2.pname
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'') HA,
STUFF((SELECT distinct ', ' + [MSW]
from piv p2
where p1.pname = p2.pname
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'') MSW,
STUFF((SELECT distinct ', ' + [SC]
from piv p2
where p1.pname = p2.pname
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'') SC
from piv p1
group by pname
見SQL Fiddle with Demo
結果是:
| PNAME | RN | LVN | HA | MSW | SC |
--------------------------------------------------------------------
| AA | AG-1W, JL-1W | SS-1M, TD-1M | LO-2W | PA-1W | SK-1M |
可以嘗試用通過...分組? – bonCodigo
Forogot詢問你的表模式定義。你能分享嗎? – bonCodigo
是否有任何通用的方法來做到這一點 – user1764540