0

我有一个像这样的 sql 表:

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
4

3 回答 3

1

Is not a good table, could be better that buy and sell to be the same collumn buy with positive values and sell with negative.

But answer your question, suppose that your table name is myTable, obs: you can execute every select separeted to understand better

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
)
于 2013-10-18T00:13:55.770 回答
0

正如其他人所指出的,您的表结构不是最佳的。

但是,鉴于您所拥有的,这将为您提供您所追求的结果。

 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
于 2013-10-18T08:35:49.977 回答
0

您应该考虑更合适的不同数据库设计(您可能需要阅读规范化),但查询如下:

SELECT t1.buy_product_total - t2.sell_product_total
FROM ProductTable t1, ProductTable t2
WHERE t1.buy_product = t2.sell_product

即您正在使用“自连接”将表连接到自身...

于 2013-10-17T23:58:34.583 回答