を使用しています。だからあなたの元の考え方にあまり影響を与えずに:
DECLARE @HMS_Chart_Clinical TABLE (
[ID] INT PRIMARY KEY NOT NULL IDENTITY (1,1),
[Temp] INT, --0,1,2,3,4
[Value] INT,
[Date] DATE,
[Time] INT, -- 0,1,2
[AMPM] INT, -- 0,1
[status] BIT,
[IPNO] INT
)
INSERT @HMS_Chart_Clinical ([Temp], [Value], [Date], [Time], [AMPM], [status], [IPNO]) VALUES (3, 125, '20161107', 2, 0, 0, 21460)
INSERT @HMS_Chart_Clinical ([Temp], [Value], [Date], [Time], [AMPM], [status], [IPNO]) VALUES (1, 26, '20161108', 2, 1, 0, 21460)
INSERT @HMS_Chart_Clinical ([Temp], [Value], [Date], [Time], [AMPM], [status], [IPNO]) VALUES (1, 99, '20161107', 1, 1, 0, 21460)
INSERT @HMS_Chart_Clinical ([Temp], [Value], [Date], [Time], [AMPM], [status], [IPNO]) VALUES (0, 106, '20161107', 0, 0, 0, 21460)
IF OBJECT_ID('tempdb..#PivotSource') IS NOT NULL
DROP TABLE #PivotSource
CREATE TABLE #PivotSource
(
Temp VARCHAR(MAX),
Value INT,
[DateTime] VARCHAR(MAX)
)
INSERT INTO #PivotSource
SELECT CASE Temp
WHEN '0' THEN 'Temperature'
WHEN '1' THEN 'PULSE RATE/MIN'
WHEN '2' THEN 'RESPIRATION/MIN'
WHEN '3' THEN 'BLOOD PRESSURE'
WHEN '4' THEN 'URINE'
END AS Temp,
Value,
CONVERT(NVARCHAR(15),[Date],103) + ' ' +
CASE [Time]
WHEN '0' THEN '2'
WHEN '1' THEN '6'
WHEN '2' THEN '10'
END + ' ' +
CASE AMPM
WHEN '0' THEN 'AM'
WHEN '1' THEN 'PM'
END AS [DateTime]
FROM @HMS_Chart_Clinical
WHERE [status] = '0'
AND IPNO='21460'
DECLARE @PivotColumns NVARCHAR(MAX)
;WITH AllDatesAndTimes AS (
SELECT DISTINCT [Date],
TimeString.[Time],
TimeString.[SortOrder]
FROM @HMS_Chart_Clinical
CROSS JOIN (SELECT '2 AM' AS [Time], 0 AS SortOrder
UNION ALL SELECT '6 AM' AS [Time], 1 AS SortOrder
UNION ALL SELECT '10 AM' AS [Time], 2 AS SortOrder
UNION ALL SELECT '2 PM' AS [Time], 3 AS SortOrder
UNION ALL SELECT '6 PM' AS [Time], 4 AS SortOrder
UNION ALL SELECT '10 PM' AS [Time], 5 AS SortOrder) TimeString
)
SELECT @PivotColumns = COALESCE(@PivotColumns + '], [', '') + CONVERT(NVARCHAR(15),[Date],103) + ' ' + [Time]
FROM AllDatesAndTimes
ORDER BY [Date],[SortOrder]
DECLARE @PivotQuery NVARCHAR(MAX) = 'SELECT * FROM #PivotSource PIVOT(MAX(Value) FOR [DateTime] IN ([' + @PivotColumns + '])) AS DATAPIVOT'
EXEC(@PivotQuery)
データを持つSQLfiddleは、その種の質問に適しています。 –
テーブルではないので、正確なテーブルはsqlserverに存在しません。 – Mihai