【发布时间】:2020-11-16 05:25:50
【问题描述】:
我在店里有一张items 的表,如果以后以不同的价格再次购买同一商品(这里的价格是如何一件商品花了商店多少钱)
id | sn | amount | price
----+------+--------+-------
1 | AP01 | 100 | 7
2 | AP01 | 50 | 8
3 | X2P0 | 200 | 12
4 | X2P0 | 30 | 18
5 | STT0 | 20 | 20
6 | PLX1 | 200 | 10
还有一张transactions的表格
id | item_id | price
----+---------+-------
1 | 1 | 10
2 | 1 | 9
3 | 1 | 10
4 | 2 | 11
5 | 3 | 15
6 | 3 | 15
7 | 3 | 15
8 | 4 | 18
9 | 5 | 22
10 | 5 | 22
11 | 5 | 22
12 | 5 | 22
和transaction.item_id references items(id)
我想按序列号 (sn) 对商品进行分组,获取它们的总和(金额)和平均价格(价格),并将其与 sold 列连接,该列计算具有引用 ID 的交易数量
我第一次用
select i.sn, sum(i.amount), avg(i.price) from items i group by i.sn;
sn | sum | avg
------+-----+---------------------
STT0 | 20 | 20.0000000000000000
PLX1 | 200 | 10.0000000000000000
AP01 | 150 | 7.5000000000000000
X2P0 | 230 | 15.0000000000000000
然后当我尝试通过交易加入它时,我得到了奇怪的结果
select i.sn, sum(i.amount), avg(i.price) avg_cost, count(t.item_id) sold, sum(t.price) profit from items i left join transactions t on (i.id=t.item_id) group by i.sn;
sn | sum | avg_cost | sold | profit
------+-----+---------------------+------+--------
STT0 | 80 | 20.0000000000000000 | 4 | 88
PLX1 | 200 | 10.0000000000000000 | 0 | (null)
AP01 | 350 | 7.2500000000000000 | 4 | 40
X2P0 | 630 | 13.5000000000000000 | 4 | 63
如您所见,只有 sold 和 profit 列显示正确的结果,sum 和 avg 显示的结果与预期不同
我无法将语句分开,因为我不确定如何将计数添加到以 item_id 作为其 id 的 sn 组?
select
j.sn,
j.sum,
j.avg,
count(item_id)
from (
select
i.sn,
sum(i.amount),
avg(i.price)
from items i
group by i.sn
) j
left join transactions t
on (j.id???=t.item_id);
【问题讨论】:
标签: sql postgresql join count sum