這應該做的伎倆......
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
歡迎#1。請花時間閱讀[如何提出一個好問題](https://stackoverflow.com/help/how-to-ask)部分。另請閱讀[如何創建最小,完整和可驗證示例](https://stackoverflow.com/help/mcve)。堆棧溢出不是一個turtorial網站,也不是一個爲你工作的網站,請自行嘗試一些東西,然後張貼你卡住的部分。 –