在 Oracle 中转换 Table?

Pivot Table in Oracle?

我有一个包含许多列的 table,用于指定错误是否有效。我需要以这样一种方式输出,即指定错误的列名称作为行以及每个错误的有效和无效字段的计数。

下面类似输入和预期输出的示例

id   name            txn_column_name  flag1 flag2 flag3 
1    Resident Count  resident_ct      Y     Y     N
2    Incident Count  incident_ct      Y     Y     Y
3    Facility Status facil_stat       N     N     N

需要输出

Col1_name Y_Count    N_Count
flag1       2            1
flag2       2            1
flag3       1            2

我们可以在这里尝试使用 Oracle 的 UNPIVOT 运算符:

SELECT
    flag AS Col1_name,
    COUNT(CASE WHEN val = 'Y' THEN 1 END) AS Y_Count,
    COUNT(CASE WHEN val = 'N' THEN 1 END) AS N_Count
FROM yourTable
UNPIVOT
(
    val FOR (flag) IN (
        flag1 AS 'flag1',
        flag2 AS 'flag2',
        flag3 AS 'flag3'
    )
)
GROUP BY
    flag
ORDER BY
    flag;

Demo

另一个直接的选项使用一系列联合:

SELECT
    'flag1' AS Col1_name,
    COUNT(CASE WHEN flag1 = 'Y' THEN 1 END) AS Y_Count,
    COUNT(CASE WHEN flag1 = 'N' THEN 1 END) AS N_Count
FROM yourTable
UNION ALL
SELECT 'flag2', COUNT(CASE WHEN flag2 = 'Y' THEN 1 END),
    COUNT(CASE WHEN flag2 = 'N' THEN 1 END)
FROM yourTable
UNION ALL
SELECT 'flag3', COUNT(CASE WHEN flag3 = 'Y' THEN 1 END),
    COUNT(CASE WHEN flag3 = 'N' THEN 1 END)
FROM yourTable
ORDER BY 1;

Demo