簡體   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