如何对 SQL 中的别名列进行算术运算

How to do an arithmetic operation with aliased column in SQL

我有一个数据库 table 如下所示:

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'

如何计算每个用户inventory/stock?

首先,您在 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<>fiddle here

您不能使用 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