Sql 计算项目总数、已售出项目(在另一个表中按id引用)并按序列号分组
我在商店里有一个Sql 计算项目总数、已售出项目(在另一个表中按id引用)并按序列号分组,sql,postgresql,join,count,sum,Sql,Postgresql,Join,Count,Sum,我在商店里有一个物品的表格,如果同一物品后来以不同的价格再次购买,那么同一物品可能有相同序列号(sn)(但ID不同)的不同条目(这里的价格是单个物品花费商店多少钱) 以及事务表 id | item_id | price ----+---------+------- 1 | 1 | 10 2 | 1 | 9 3 | 1 | 10 4 | 2 | 11 5 | 3 | 15 6 |
物品的表格
,如果同一物品后来以不同的价格再次购买,那么同一物品可能有相同序列号(sn)(但ID不同)的不同条目(这里的价格是单个物品花费商店多少钱)
以及事务表
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\u id引用项目(id)
我想按序列号(sn)对项目进行分组,得到它们的总和(金额)和平均值(价格),并将其与一个sell
列连接起来,该列统计引用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
如您所见,只有已售出
和利润
列显示正确的结果,总和和平均值显示的结果与预期不同
我无法分离这些语句,因为我不确定如何将计数添加到以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);
两个表中都有多个匹配项,因此,
join
将行相乘(并最终生成wron结果)。我建议先加入,然后聚合:
select
sn,
sum(amount) total_amount,
avg(price) avg_price,
sum(no_transactions) no_transactions
from (
select
i.*,
(
select count(*)
from transactions t
where t.item_id = i.id
) no_transactions
from items i
) t
group by sn
这使0成为所有行的无\u事务。。。交易应该是交易,它是有效的,我会把它标记为接受的答案,谢谢
select
sn,
sum(amount) total_amount,
avg(price) avg_price,
sum(no_transactions) no_transactions
from (
select
i.*,
(
select count(*)
from transactions t
where t.item_id = i.id
) no_transactions
from items i
) t
group by sn