0
這似乎很簡單,但我不能得到我需要的結果...從單個文本列創建多列,有點像樞軸
我有一個類別,日期和一個代碼:
Cat Dt Code
A 2013-07-02 X1
A 2013-07-02 Y4
A 2013-07-02 L2
A 2013-07-02 M8
A 2013-07-02 H7
A 2013-07-02 P4
,並希望這樣的回報是:
Cat Dt Code1 Code1 Code3 Code4 Code5 Code6
A 2013-07-02 X1 Y4 L2 M8 H7 P4
- 一些SQL與...
CREATE TABLE dbo.test1 (Cat VARCHAR(8), Dt DATE, Code VARCHAR(8))
INSERT INTO dbo.test1 (Cat, Dt, Code)
-- This set should return a value in all 6 Code columns...
SELECT 'A', '2013-07-02', 'X1'
UNION SELECT 'A', '2013-07-02', 'Y4'
UNION SELECT 'A', '2013-07-02', 'L2'
UNION SELECT 'A', '2013-07-02', 'M8'
UNION SELECT 'A', '2013-07-02', 'H7'
UNION SELECT 'A', '2013-07-02', 'P4'
-- This set should have a NULL in Code6 since there are only 5 codes
UNION SELECT 'B', '2013-07-03', 'Y6'
UNION SELECT 'B', '2013-07-03', 'D5'
UNION SELECT 'B', '2013-07-03', 'F8'
UNION SELECT 'B', '2013-07-03', 'G9'
UNION SELECT 'B', '2013-07-03', 'J2'
-- This set should have a NULL in Code6 since there are only 5 distinct codes
UNION SELECT 'C', '2013-07-04', 'D1'
UNION SELECT 'C', '2013-07-04', 'D1'
UNION SELECT 'C', '2013-07-04', 'U3'
UNION SELECT 'C', '2013-07-04', 'T9'
UNION SELECT 'C', '2013-07-04', 'G4'
-- This set has 7, but I only care about 6 of them. Which 6 doesn't matter, just any of the 6 codes
UNION SELECT 'D', '2013-07-05', 'T1'
UNION SELECT 'D', '2013-07-05', 'Y2'
UNION SELECT 'D', '2013-07-05', 'U3'
UNION SELECT 'D', '2013-07-05', 'I9'
UNION SELECT 'D', '2013-07-05', 'P8'
UNION SELECT 'D', '2013-07-05', 'L7'
UNION SELECT 'D', '2013-07-05', 'J6'
測試
任何幫助,將不勝感激
什麼是確定'代碼1 ... Code6'值的順序?另外,您使用的是什麼RDBMS(YYYY-MM-DD可能提示MySQL,儘管'dbo.'建議MS SQL Server) –
對不起,順序無關緊要。很少會超過6個,如果有的話,我可以丟棄超過6個。我正在使用SQL Server 2008 R2。 – user2701201