繁体   English   中英

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

[英]How get two fields of different records in one record Mysql

我有一张包含此内容的表格(还有更多不相关的字段):

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

imei 字段只能作为一次购买(invoice_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

我想要获得的是以下结果,一个字段是购买价格,另一个字段是销售价格,另一个字段是这两个字段的利润和 model 字段。

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

您应该使用同一个表 2,使用别名并按销售和购买过滤

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' 

你的桌子设计一团糟。 如果您可以更改它,我会将这张表分成三个单独的表格,一张用于购买,一张用于销售,一张用于电话。

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

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'

希望我有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM