2
刪除charecters我與佈局如下表:從串聯
CREATE TABLE dbo.tbl (
Ten_Ref VARCHAR(20) NOT NULL,
Benefit VARCHAR(20) NOT NULL
);
INSERT INTO dbo.tbl (Ten_Ref, Benefit)
VALUES ('1', 'HB'),
('1', 'WTC'),
('1', 'CB'),
('2', 'CB'),
('2', 'HB'),
('3', 'WTC');
我然後運行該代碼來執行轉換和連接(我需要的所有服務信息的一個領域」
with [pivot] as
(
SELECT Ten_Ref
,[HB] = (Select Benefit FROM tbl WHERE t.Ten_Ref = Ten_Ref and Benefit = 'HB')
,[CB] = (Select Benefit FROM tbl WHERE t.Ten_Ref = Ten_Ref and Benefit = 'CB')
,[WTC] = (Select Benefit FROM tbl WHERE t.Ten_Ref = Ten_Ref and Benefit = 'WTC')
/*Plus 7 more of these*/
FROM tbl as t
GROUP BY Ten_Ref
)
select p.ten_Ref
/*A concatenation to put them all in one field, only problem is you end up with loads of spare commas*/
,[String] = isnull (p.HB,0) + ',' + isnull (p.cb,'') + ',' + isnull (p.wtc,'')
from [pivot] as p
我的問題是不是每個ten_ref有所有優點的連接。
使用此代碼,其中還有一定的差距Ø r NULL然後我最終得到大量的雙逗號,例如'HB ,, WTC'
我怎樣才能得到它,所以它只有一個逗號,而不管每個租約有多少好處?
謝謝 - (第一篇文章)
謝謝斯蒂芬。這解決了它。 我基於我的原始解決方案在這個線程的答案:http://stackoverflow.com/questions/24470/sql-server-pivot-examples – spench