这看起来很简单,但我无法得到我需要的结果......
我有一个类别,日期和代码:
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'
任何帮助将不胜感激
答案 0 :(得分:2)
这是不使用PIVOT
的一种方式:
;WITH CTE AS
(
SELECT *,
RN=ROW_NUMBER() OVER(PARTITION BY Cat, Dt ORDER BY Cat, Dt)
FROM dbo.test1
)
SELECT Cat,
Dt,
MIN(CASE WHEN RN = 1 THEN Code END) Code1,
MIN(CASE WHEN RN = 2 THEN Code END) Code2,
MIN(CASE WHEN RN = 3 THEN Code END) Code3,
MIN(CASE WHEN RN = 4 THEN Code END) Code4,
MIN(CASE WHEN RN = 5 THEN Code END) Code5,
MIN(CASE WHEN RN = 6 THEN Code END) Code6
FROM CTE
GROUP BY Cat,
Dt