我正在尝试获取下面的查询输出,请帮助我
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');
以下是我正在使用的查询
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
答案 0 :(得分:4)
尝试这个简单的查询:
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)
如果您想Subtotal
代替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)