Mysql 计算同一表中不同列的SQL表解决方案
我有一个sql表,如:Mysql 计算同一表中不同列的SQL表解决方案,mysql,sql,Mysql,Sql,我有一个sql表,如: id buy_product buy_product_total sell_product sell_product_total 1 apple 5 2 banana 8 3 cake 20 4
id buy_product buy_product_total sell_product sell_product_total
1 apple 5
2 banana 8
3 cake 20
4 apple 1
5 cake 2
6 apple 2
我的问题是,我想显示产品名称和剩余产品数量。比如:
product_name left
apple 6
cake 18
如何使用sql查询显示类似于该解决方案的解决方案
我创建表作为回答者,如下所示:
买桌子
id product_name total
1 apple 5
2 banana 8
3 cake 20
4 apple 2
卖桌子
id product_name total
1 apple 1
2 cake 2
我想要这样的桌子
product_name left
apple 6
banana 8
cake 18
你应该考虑一个更合适的数据库设计(你可能想读规范化),但是查询如下:
SELECT t1.buy_product_total - t2.sell_product_total
FROM ProductTable t1, ProductTable t2
WHERE t1.buy_product = t2.sell_product
i、 e.您正在使用“自联接”将表联接到它本身……不是一个好的表,最好是买卖是相同的,即买入为正值,卖出为负值 但是回答您的问题,假设您的表名是myTable, obs:您可以执行每个select separeted以更好地理解
select buy_product as product_name, (buy_total - sell_total) as left
from (
(select buy_product, sum(buy_product_total) as buy_total
from myTable where buy_product_total is not null group by buy_product) as buy_list
inner join
(select sell_product, sum(sell_product_total) as sell_total
from myTable where sell_product_total is not null group by sell_product) as sell_list
on buy_list.buy_product = sell_list.sell_product
)
正如其他人所指出的,您的表结构不是最佳的 然而,考虑到你所拥有的,这会给你你想要的结果
select product, sum(total) from
(
select buy_product as product, buy_product_total as total
from yourtable
where buy_product is not null
union
select sell_product, -sell_product_total
from yourtable
where sell_product is not null
) v
group by product
或者,用你的两张桌子
select product_name, sum(total) from
(
select product_name, total
from buy_table
union
select product_name, -total
from sell_table
) v
group by product_name
您可能应该将这些数据放在两个不同的表中,一个用于购买,另一个用于销售。然后您可以通过连接两个表来实现这一点。您使用的是什么数据库?您用MySQL和SQL Server标记了这个,根据您的产品,可能有特定于数据库的解决方案可供您使用。我使用的是MySQL。但问题是,我上传了一个excel文件,如果里面有相同的产品,我会分组和求和(购买产品)。谢谢,我似乎要做两个表。你也认为我必须有两个表。你改变了原来问题的结构。我修复了表,但我仍然有一个问题。如果你检查你能看到,我变得有点疯狂