Select rows with subtotals maintaining proper order

≯℡__Kan透↙ 提交于 2019-12-12 14:00:07

问题


I am trying to get the output of my query as below please help me

partno    value     value1    phaseid
ABCD      10        11        A
ABCD      11        12        B
Subtotal  21        23    
DEFG      20        21        C
Subtotal  20        21
IJKL      30        31        A
IJKL      31        32        D
Subtotal  61        63


CREATE TABLE test_table
(
  partno text,
  value bigint,
  value1 bigint,
  phaseid text
)

INSERT INTO test_table(
            partno, value, value1, phaseid)
    VALUES ('ABCD', 10, 11, 'A'),('ABCD', 11, 12, 'B'),('DEFG', 20, 21, 'C'),('IJKL', 30, 31, 'A'),
    ('IJKL', 31, 321, 'D');

Below is the Query i am using

Select a.partno,a.value,a.value1,b.phaseid
from (
select partno,value,value1 from test_table a
Union all
Select 'Subtotal',Sum(value),sum(value1) from test_table a
Group By partno
) as a
Left Join test_table b USING (partno)
order by  value,value1


回答1:


Try this simple query:

select partno, value, value1, phaseid
from test_table a
union all
select partno || ' Subtotal', sum(value), sum(value1), null
from test_table a
group by 1
order by 1, 4

    partno     | value | value1 | phaseid 
---------------+-------+--------+---------
 ABCD          |    10 |     11 | A
 ABCD          |    11 |     12 | B
 ABCD Subtotal |    21 |     23 | 
 DEFG          |    20 |     21 | C
 DEFG Subtotal |    20 |     21 | 
 IJKL          |    30 |     31 | A
 IJKL          |    31 |     32 | D
 IJKL Subtotal |    61 |     63 | 
(8 rows)

If you want to have Subtotal instead of ABCD Subtotal:

select 
    case when strpos(partno, 'Subtotal') > 0 then 'Subtotal' else partno end partno,
    value, value1, phaseid
from (
    select partno, value, value1, phaseid
    from test_table a
    union all
    select partno || ' Subtotal', sum(value), sum(value1), null
    from test_table a
    group by 1
    order by 1, 4
    ) sub   

  partno  | value | value1 | phaseid 
----------+-------+--------+---------
 ABCD     |    10 |     11 | A
 ABCD     |    11 |     12 | B
 Subtotal |    21 |     23 | 
 DEFG     |    20 |     21 | C
 Subtotal |    20 |     21 | 
 IJKL     |    30 |     31 | A
 IJKL     |    31 |     32 | D
 Subtotal |    61 |     63 | 
(8 rows)


来源:https://stackoverflow.com/questions/32989843/select-rows-with-subtotals-maintaining-proper-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!