oracle 使用较少行数中的分组值来减少行数的SQL查询

fwzugrvs  于 2023-08-04  发布在  Oracle
关注(0)|答案(1)|浏览(115)

我有一组数据,如下所示


的数据
我想减少其中的行数。如果可以减少到单行,则将其视为最佳情况。
最终的数据集应该类似于

我尝试了SQL中的Min和Max函数。但我不想丢失任何数据。只是想填充空白单元格,以便报表的可读性。
如果任何人需要样本数据,那么你可以使用下面的查询

select * from
(
SELECT 9999 as primary_key ,1 AS column_1, 2 as column_2, NULL  as column_3, NULL as column_4 FROM DUAL
UNION ALL
SELECT 9999, NULL, NULL, 3, 4 FROM DUAL
UNION ALL
SELECT 9999, 5, 6, NULL, NULL FROM DUAL
)

字符串

vdgimpew

vdgimpew1#

我建议将当前数据转换为排除NULL值的“未透视状态”,同时在混合中添加一个行号。然后,一旦可用,然后使用primary_key和行号将该中间结果重新透视为所需的最终格式:

WITH UNPIV AS (
    SELECT PRIMARY_KEY, 'column_1' AS COLUMN_NAME, column_1 AS COLUMN_VALUE
           , ROW_NUMBER() OVER(PARTITION BY PRIMARY_KEY ORDER BY column_1) AS RN
    FROM your_table
    WHERE column_1 IS NOT NULL
    
    UNION ALL
    
    SELECT PRIMARY_KEY, 'column_2' AS COLUMN_NAME, column_2 AS COLUMN_VALUE
           , ROW_NUMBER() OVER(PARTITION BY PRIMARY_KEY ORDER BY column_2) AS RN
    FROM your_table
    WHERE column_2 IS NOT NULL
    
    UNION ALL
    
    SELECT PRIMARY_KEY, 'column_3' AS COLUMN_NAME, column_3 AS COLUMN_VALUE
           , ROW_NUMBER() OVER(PARTITION BY PRIMARY_KEY ORDER BY column_3) AS RN
    FROM your_table
    WHERE column_3 IS NOT NULL
    
    UNION ALL
    
    SELECT PRIMARY_KEY, 'column_4' AS COLUMN_NAME, column_4 AS COLUMN_VALUE
           , ROW_NUMBER() OVER(PARTITION BY PRIMARY_KEY ORDER BY column_4) AS RN
    FROM your_table
    WHERE column_4 IS NOT NULL
    )
SELECT PRIMARY_KEY, 
       MAX(CASE WHEN COLUMN_NAME = 'column_1' THEN COLUMN_VALUE END) AS COLUMN_1,
       MAX(CASE WHEN COLUMN_NAME = 'column_2' THEN COLUMN_VALUE END) AS COLUMN_2,
       MAX(CASE WHEN COLUMN_NAME = 'column_3' THEN COLUMN_VALUE END) AS COLUMN_3,
       MAX(CASE WHEN COLUMN_NAME = 'column_4' THEN COLUMN_VALUE END) AS COLUMN_4
FROM UNPIV
GROUP BY PRIMARY_KEY, RN
ORDER BY PRIMARY_KEY, RN

字符串
| 列_1| COLUMN_2| COLUMN_3|列_4| COLUMN_4 |
| --|--|--|--| ------------ |
| 一个|二个|三个|四个| 4 |
| 五个|六个| * 空 | 空 *| null |
fiddle
请注意,这些行中的值的排列由row_number()计算确定。因此,不能保证值将重新对齐到它们所源自的同一行中。

相关问题