每个列的SQL数据透视表总数

问题描述 投票:0回答:2

所以我有这个表有动态标题。

enter image description here

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

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但它不起作用。

enter image description here

我试过这个查询:

    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查询中创建附加部分以创建目标查询的第一行。

sql oracle pivot rollup dynamic-columns
2个回答
0
投票

最快的方法是复制相同的查询。就像是:

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()中括号之间添加cyour列名称


0
投票

此查询有效:

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构建动态查询并检查语法是否正确。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.