postgresql 如何从同一个表中生成/创建同一行,其中一个列条件已更改

qlzsbp2j  于 2023-04-22  发布在  PostgreSQL
关注(0)|答案(2)|浏览(105)

我的数据看起来像这样
| 日期|范畴|子范畴|价格|
| --------------|--------------|--------------|--------------|
| 20230510|一个|LMN| 10个|
| 20230510|一个|PQR|二十|
| 20230511|一个|LMN|五十|
| 20230511|一个|PQR| 10个|
在我的表中,我得到子类别LMN和PQR沿着价格,我需要引入行ALL,并使用优化查询添加LMN和PQR子类别的价格
我的预期输出是这样的
| 日期|范畴|子范畴|价格|
| --------------|--------------|--------------|--------------|
| 20230510|一个|LMN| 10个|
| 20230510|一个|PQR|二十|
| 20230510|一个|全部|三十|
| 20230511|一个|LMN|五十|
| 20230511|一个|PQR| 10个|
| 20230511|一个|全部|六十|
我尝试使用UNIONALL生成一行到ALL,并在类别级别添加价格并显示,但无论如何,我可以不使用UNIONALL或SELF JOIN来做同样的事情,从而减少表扫描
我试过了-

select date,
category,
'ALL' as subcategory
sum(price)
from table
group by date,category
UNION ALL
select date,
category,
subcategory,
price
from table;
t3irkdon

t3irkdon1#

你可以使用rollup:

with mytable as (select * from (values
                      ('20230510', 'A', 'LMN', 10),
                      ('20230510', 'A', 'PQR', 20),
                      ('20230511', 'A', 'LMN', 50),
                      ('20230511', 'A', 'PQR', 10)) x(date, category,   subcategory,    price))

select date, category, subcategory, sum(price) as price
from mytable
group by  rollup (date, category, subcategory)
order by date,category, subcategory;
huwehgph

huwehgph2#

使用条件聚合仅获取LMNPQR的总价:

select *
from mytable
WHERE subcategory in ('LMN','PQR')
UNION ALL
select date, category, 'ALL' as subcategory, sum(case when subcategory in ('LMN','PQR') then price else 0 end)
from mytable
group by date, category
order by date

如果不感兴趣,按子类别过滤数据,则:

select *
from mytable
UNION ALL
select date, category, 'ALL' as subcategory, sum(price)
from mytable
group by date, category
order by date

Demo here

相关问题