我的資料在testtable:
| FechaRegistro | IdRecordRedcap | FechaRegistro | diario_total_pruebas | diario_pruebas_negativas | diario_pruebas_rechazadas |
|---|---|---|---|---|---|
| 15 | 15 | 2022-01-06 | 510 | 384 | 空值 |
我需要在沒有該UNPIVOT功能的情況下取消透視以下資料
| FechaRegistro | IdRecordRedcap | 變數 | 價值 |
|---|---|---|---|
| 2022-01-06 | 15 | diario_total_pruebas | 510 |
| 2022-01-06 | 15 | diario_pruebas_negativas | 384 |
| 2022-01-06 | 15 | diario_pruebas_rechazadas | 空值 |
此 db<>fiddle 中的結構和示例資料
uj5u.com熱心網友回復:
-- on SQL Server 2000 you must have a death wish
SELECT FechaRegistro, IdRecordRedcap,
Var = 'diario_total_pruebas',
Value = diario_total_pruebas
FROM dbo.testtable
UNION ALL
SELECT FechaRegistro, IdRecordRedcap,
Var = 'diario_pruebas_negativas',
Value = diario_pruebas_negativas
FROM dbo.testtable
UNION ALL
SELECT FechaRegistro, IdRecordRedcap,
Var = 'diario_pruebas_rechazadas',
Value = diario_pruebas_rechazadas
FROM dbo.testtable;
公平地說,要讓UNPIVOT本世紀發布的版本的解決方案正確處理NULLs,它并沒有那么干凈:
-- on SQL Server 2005 and later
;WITH x AS
(
SELECT FechaRegistro, IdRecordRedcap,
diario_total_pruebas = COALESCE(diario_total_pruebas, -1),
diario_pruebas_negativas = COALESCE(diario_pruebas_negativas, -1),
diario_pruebas_rechazadas = COALESCE(diario_pruebas_rechazadas, -1)
FROM dbo.testtable
)
SELECT FechaRegistro, IdRecordRedcap,
Var, Value = NULLIF(Value, -1)
FROM x UNPIVOT
(
Value FOR Var IN
(
diario_total_pruebas,
diario_pruebas_negativas,
diario_pruebas_rechazadas
)
) AS u;
兩種情況下的輸出:
| FechaRegistro | IdRecordRedcap | 變數 | 價值 |
|---|---|---|---|
| 2022-01-06 | 15 | diario_total_pruebas | 510 |
| 2022-01-06 | 15 | diario_pruebas_negativas | 384 |
| 2022-01-06 | 15 | diario_pruebas_rechazadas | 空值 |
- 示例db<>fiddle
uj5u.com熱心網友回復:
UNPIVOT 是在 SQL Server 2005 中引入的。如果你真的使用 SQL Server 2000,你會遇到比 UNPIVOTing 更大的問題。一臺裝有 SQL Server Express 的筆記本電腦比 20 年前任何可用的筆記本電腦都更強大,具有更快的磁盤、更多的 RAM 和 CPU 內核(當時還沒有多核)。而且也更安全。
如果沒有 UNPIVOT,您可能必須撰寫與要取消透視的列一樣多的查詢,并將它們與UNION ALL:
select FechaRegistro,IdRecordRedcap,'diario_total_pruebas' as Var,
diario_total_pruebas as Value
from testtable
UNION ALL
select FechaRegistro,IdRecordRedcap,'diario_pruebas_negativas' as Var,
diario_pruebas_negativas as Value
from testtable
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/410553.html
標籤:
上一篇:SQL-在同一列中回傳多個值
