如何在一条记录Mysql中获取不同记录的两个字段

时间:2019-10-16 12:45:07

标签: mysql record

我有一个具有此内容的表(有更多不相关的字段):

交易可以是购买或出售。购买可以是id_factura或id_albaran,如果购买的是id_factura,id_albaran为Null,反之亦然,则销售额相同。但是销售可以有两个具有相同imei的记录,如我们在示例中看到的:id_purchasesale 2和3(在这种情况下,它将始终具有相同的价格,在示例250中)。

imei字段只能作为一次购买(发票_id或albaran_id)存在,或者作为一次或两次销售存在。

如果有购买但没有出售相同的imei,则不必出示它。

表购买

id_purchasesale    transaction    id_factura    id_albaran    Model      imei     price
  1                purchase         1            Null       Samsung      30888     200 
  2                sale             1            Null       Samsung      30888     250
  3                sale             Null         1          Samsung      30888     250  
  4                purchase         Null         1          Apple        52101     300
  5                sale             1            Null       Apple        52101     380  
  6                purchase         2            Null       Motorola     77520     300
  7                sale             2            Null       Motorola     77520     350
  8                purchase         3            Null       Xiaomi       29102     150

我想要获得的结果如下:一个带有购买价格的字段,另一个带有销售价格的字段,另一个带有这两个字段和模型字段的利润的字段。

imei        price_purchase    price_sale   profit   Model 
30888            200             250        50      Samsung
52101            300             380        80      Apple
77520            300             350        50      Xiaomi

3 个答案:

答案 0 :(得分:1)

您可以在下面尝试-

select imeid,
       max(case when transaction='purchase' then price else 0 end) as purchase_price,
       max(case when transaction='sale' then price else 0 end) as sale_price,
       max(case when transaction='sale' then price else 0 end)-max(case when transaction='purchase' then price else 0 end) as profit,
       model
from tablename
where transaction in ('purchase','sale')
group by imeid,model
having count(distinct transaction)=2

答案 1 :(得分:1)

您可以使用同一张表,两个使用别名并按买卖进行过滤

select  a.imei
 , a.model
 , a.price as  price_purchase
 , b.price as price_sale
 , b.price - a.price  as profit
from  purchasesale a 
inner join  purchasesale b  on a.imei = b.imei 
    and a.transaction ='purchase'  
      and b.transaction ='sale' 

答案 2 :(得分:1)

您的餐桌设计一团糟。如果可以更改它,我会将此表分为三个单独的表,一个用于购买,一个用于销售,另一个用于电话。

但是,在当前情况下,这应该可以满足您的要求:

SELECT
 t1.imei as imei,
 t1.price as price_purchase,
 t2.price as price_sale,
 (t2.price - t1.price) as profit,
 t1.model as model
FROM purchasesale t1, purchasesale t2
WHERE t1.imei = t2.imei and
 t1.transaction = 'purchase' and
 t2.transaction = 'sale'

希望我能帮上忙!