只是猜测,但也许
with tb1 as (
select product_name, SUM(product_value) as sell
from vendor
where transaction_type='sell'
group by product_name
),
tb2 as (
select product_name, SUM(product_value) as buy
from vendor
where transaction_type='buy'
group by product_name
)
select tb1.product_name, tb1.sell, tb2.buy, (tb2.buy - tb1.sell) as profit
from tb1 left join tb2 on tb1.product_name=tb2.product_name
使用此设置:
create table vendor (product_name text, product_value int, transaction_type text)
insert into vendor values ('ABC',3196,'sell'),('XYZ',3196,'sell'),('PQR',3196,'sell'),('ABC',2365,'buy'),('ABC',2365,'buy')
查询返回
product_name sell buy profit
ABC 3196 4730 1534
PQR 3196 NA NA
XYZ 3196 NA NA
编辑:这也适用于 MySQL,不知道为什么它不适合你。
Docker 设置:
r2@d2sb2:~$ docker pull mysql:latest
latest: Pulling from library/mysql
...
Digest: sha256:99e0989e7e3797cfbdb8d51a19d32c8d286dd8862794d01a547651a896bcf00c
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest
r2@d2sb2:~$ docker run --rm -p 3306:3306 --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:latest
2e93acda94fdb386a9205ccda8df9b4f47b5f6a9bbdd159f84550418dff4a56e
然后在 SQL 中:
SHOW VARIABLES LIKE 'version';
# Variable_name Value
# version 8.0.26
create schema stackoverflow;
use stackoverflow;
create table vendor (product_name text, product_value int, transaction_type text)
insert into vendor values ('ABC',3196,'sell'),('XYZ',3196,'sell'),('PQR',3196,'sell'),('ABC',2365,'buy'),('ABC',2365,'buy')
with tb1 as (
select product_name, SUM(product_value) as sell
from vendor
where transaction_type='sell'
group by product_name
),
tb2 as (
select product_name, SUM(product_value) as buy
from vendor
where transaction_type='buy'
group by product_name
)
select tb1.product_name, tb1.sell, tb2.buy, (tb2.buy - tb1.sell) as profit
from tb1 left join tb2 on tb1.product_name=tb2.product_name
# product_name sell buy profit
# ABC 3196 4730 1534
# XYZ 3196 NA NA
# PQR 3196 NA NA
(注意:我在 R DBI 客户端中逐一运行命令,而不是在 mysql 控制台中;我怀疑除了 R 的 NA 作为空值之外它会有所不同。仅供参考。 )
由于您的实例似乎在没有HAVING 的情况下使用SUM 存在一些问题,因此该查询模式会产生相同的结果:
with tb1 as (
select product_name, SUM(product_value) as sell
from vendor
group by product_name, transaction_type
having transaction_type='sell'
),
tb2 as (
select product_name, SUM(product_value) as buy
from vendor
group by product_name, transaction_type
having transaction_type='buy'
)
select tb1.product_name, tb1.sell, tb2.buy, (tb2.buy - tb1.sell) as profit
from tb1 left join tb2 on tb1.product_name=tb2.product_name