SQL 数据透视 table 每列总计

SQL pivot table total per column

所以我有这个 table 具有动态 headers。

下面的查询用于生成将用于 table 查询的日期。

select listagg(INSERT_DATE,
''',''') WITHIN GROUP(ORDER BY INSERT_DATE)
from (select distinct INSERT_DATE from TEST_TBL order by INSERT_DATE asc)

上面查询的结果用于下面的 in 子句。

select * from (select log, lot, insert_date from TEST_TBL)
pivot(count(distinct log || insert_date)
for(insert_date) in ('17-JAN-19', '21-JAN-19', '22-JAN-19'))

现在,我想要这样的结果,其中每列的总数将显示在所有行的末尾。我尝试使用 GROUP BY ROLLUP 但它不起作用。

我试过这个查询:

    select * 
    from (select * from (select log, lot, insert_date from TEST_TBL) pivot(count(distinct log || insert_date)
    for(insert_date) in ('17-JAN-19', '21-JAN-19', '22-JAN-19')))
    group by rollup (log); 

有人可以帮我解决我应该使用什么查询吗?谢谢。

编辑:我使用了@q4za4 的解决方案并得出了这个最终查询

from   (select *
            from   (select log,
                           lot,
                           insert_date
                    from   TEST_TBL)
            pivot(
                    count(distinct lot || insert_date)
                    for   (insert_date) 
                    in    ('17-JAN-19','21-JAN-19','22-JAN-19'))
    )
    UNION ALL
    select 'TOTAL # OF LOGS',
           sum(jan1719),sum(jan2119),sum(jan2219)
    FROM   (select *
            from   (select log,
                           lot,
                           insert_date
                    from   TEST_TBL)
            pivot(
                    count(distinct lot || insert_date)
                    for   (insert_date) 
                    in    (
                    '17-JAN-19' as jan1719,'21-JAN-19' as jan2119,'22-JAN-19' as jan2219
                    )))

也感谢@Ponder Stibbons 的解决方案,它也帮助了我,让我想到在 listagg-query 中添加额外的部分来创建目标查询的第一行。

最快的方法是重复相同的查询。类似于:

select *
from   (select log,
               lot,
               insert_date
        from   TEST_TBL)
pivot(
        count(distinct log || insert_date)
        for   (insert_date) 
        in    ('17-JAN-19', '21-JAN-19', '22-JAN-19'))
)
UNION ALL
select NULL,
       sum(),
       sum(),
       sum(),
FROM   (
        select *
        from   (select log,
                       lot,
                       insert_date
                from   TEST_TBL)
        pivot(
                count(distinct log || insert_date)
                for   (insert_date) 
                in    ('17-JAN-19', '21-JAN-19', '22-JAN-19'))
       )

在 sum() 的括号之间添加您的列名

此查询有效:

select lot, sum(d17) sd17, sum(d22) sd22, sum(d23) sd23
  from test_tbl
  pivot(count(distinct log) for(insert_date) in (date '2019-01-17' d17, 
                                                 date '2019-01-22' d22, 
                                                 date '2019-01-23' d23))
  group by rollup(lot)

dbfiddle demo

因此,如果您动态生成日期,您还必须在 listagg-query 中添加其他部分以创建目标查询的第一行,就像您对 in 子句所做的那样。您可以根据需要为列设置别名,然后尝试构建动态查询并使用 dbms_output.

检查语法是否正确