【问题标题】:count total items, sold items (in another table reference by id) and grouped by serial number计算项目总数、已售项目(在另一个表中按 id 引用)并按序列号分组
【发布时间】: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

如您所见,只有 soldprofit 列显示正确的结果,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


    【解决方案1】:

    两个表中有多个匹配项,因此 join 将行相乘(并最终产生错误的结果)。我建议先加入,然后再聚合:

    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 作为所有行的 no_transactions...事务应该是事务,并且它有效,我会将其标记为已接受的答案,谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    • 2023-04-02
    • 2020-12-01
    • 2014-02-07
    • 2017-06-02
    相关资源
    最近更新 更多