我有一个问题要问:
Time Pass Fail
-------------------------
08:30 10 2
09:30 12 1
10:30 20 0
11:30 30 40
我正在尝试将行转换为列并在下面显示此类信息
08:30 09:30 10:30 11:30
------------------------------
10 12 20 30
2 1 0 40
请帮助我!
谢谢!
答案 0 :(得分:0)
这应该可以解决问题......
IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL
DROP TABLE #TestData;
CREATE TABLE #TestData (
[Time] DATETIME NOT NULL,
Pass INT NOT NULL,
Fail INT NOT null
);
INSERT #TestData (Time, Pass, Fail) VALUES
('08:30',10, 2),
('09:30',12, 1),
('10:30',20, 0),
('11:30',30, 40);
SELECT
[P/F] = CASE WHEN pf.id = 1 THEN 'Pass' ELSE 'Fail' END,
[08:30] = MAX(CASE WHEN td.[Time] = '08:30' THEN pf.Value END),
[09:30] = MAX(CASE WHEN td.[Time] = '09:30' THEN pf.Value END),
[10:30] = MAX(CASE WHEN td.[Time] = '10:30' THEN pf.Value END),
[11:30] = MAX(CASE WHEN td.[Time] = '11:30' THEN pf.Value END)
FROM
#TestData td
CROSS APPLY ( VALUES (1, td.Pass), (2, td.Fail) ) pf (id, Value)
GROUP BY
pf.id;
结果...
P/F 08:30 09:30 10:30 11:30
---- ----------- ----------- ----------- -----------
Pass 10 12 20 30
Fail 2 1 0 40