【问题标题】:How to do an arithmetic operation with aliased column in SQL如何在 SQL 中使用别名列进行算术运算
【发布时间】:2021-06-21 12:01:34
【问题描述】:

我有一个如下的数据库表:

id received_by sent_by amount product_id
1  1           2       10     1
2  1           3       12     1
3  2           1       5      1
4  3           1       8      2

这里,received_bysent_by 是分别接收和发送产品的两个用户ID。我想通过从收到的金额中减去发送的金额来计算单个用户的每个产品的总金额。 我当前的查询如下所示:

select
    product_id,
    (received - sent) as quantity,
    case(when received_by = 1 then amount end) as received,
    case(when sent_by = 1 then amount end) as sent
group by
    product_id;

这里我得到一个错误,Unknown column 'received' in 'field list'

如何计算每个用户的库存/库存?

【问题讨论】:

  • 你用的是哪个版本的mysql?
  • 请分享您想要的输出数据。

标签: mysql sql group-by subquery


【解决方案1】:

首先,您在 group by 之前错过了查询中的 from 子句。其次,您不能在同一个 select 语句中使用列别名(接收、发送)。

 create table mytable(id int, received_by int, sent_by int, amount int, product_id int);
 insert into mytable values(1,  1,           2,       10,     1);
 insert into mytable values(2,  1,           3,       12,     1);
 insert into mytable values(3,  2,           1,       5,      1);
 insert into mytable values(4,  3,           1,       8,      2);

查询:

  select product_id, (coalesce(received,0)-coalesce(sent,0)) as Quantity, coalesce(received,0) received,coalesce(sent)sent
from 
(       select
            product_id,
            sum(case when received_by = 1 then amount end) as received,
            sum(case when sent_by = 1 then amount end) as sent
        from mytable
        group by
            product_id

)t;
 

输出:

    |product_id | Quantity | received | sent|
    |-----------|----------|----------|-----|
    |         1 |       17 |       22 |    5|
    |         2 |       -8 |        0 |    8|

db小提琴here

【讨论】:

    【解决方案2】:

    您不能使用SELECT 列表中的计算列。
    你还需要聚合函数SUM()

    一种方法是使用子查询:

    select *, (received - sent) as quantity
    from (
      select product_id, 
             sum(case when received_by = 1 then amount else 0 end) as received, 
             sum(case when sent_by = 1 then amount else 0 end) as sent 
      from tablename
      where 1 in (received_by, sent_by)
      group by product_id
    ) t
    

    或者:

    select product_id, 
           sum(case when received_by = 1 then amount else -amount end) as quantity,
           sum(case when received_by = 1 then amount else 0 end) as received, 
           sum(case when sent_by = 1 then amount else 0 end) as sent 
    from tablename
    where 1 in (received_by, sent_by)
    group by product_id
    

    请参阅demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多