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

How get two fields of different records in one record Mysql

我有一个table这个内容(还有更多不相关的字段):

交易可以是购买或销售。一个purchase可以是id_factura或者id_albaran,如果是purchaseid_factura,id_albaran就是Nul​​l,反之,sale也是一样的。但是一次销售可以有两个具有相同 imei 的记录,正如我们在示例中看到的:id_purchasesale 2 和 3(在这种情况下它总是具有相同的价格,例如 250)。

imei 字段只能作为一次购买(invoice_id 或 albaran_id)和一次或两次销售存在。

如果同一 imei 有购买而没有销售,则无需出示。

TABLE 采购销售

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

你可以试试下面的-

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

你应该使用相同的 table 两个使用别名并按买卖过滤

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' 

您的 table 设计一团糟。如果您可以更改它,我会将此 table 拆分为三个单独的 table,一个用于购买,一个用于销售,一个用于手机。

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

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'

希望我有所帮助!