2017-04-14 50 views
1

嘿,我真的很奇怪的邏輯可以有人幫我寫查詢。我想總結regOption的所有價格,其中regOption也有xnCoupon(優惠券和regOption分享同一個entry_id)。在這種的exaple想量139MySql基於其他列值查詢求和行

|id   |trans_id| entry_id |type  | Price 
------------------------------------------------------ 
|43575855 |24419612| 26898343 |regOption| 139   
|43575856 |24419612| 26898343 |xnCoupon | 50 

|43575857 |24419612| 26898346 |regOption| 139   
|43575858 |24419612| 26898346 |Tshirt | 10 
在第二個例子中

希望量將是278

|id   |trans_id| entry_id |type  | Price 
------------------------------------------------------ 
|43575855 |24419612| 26898343 |regOption| 139   
|43575856 |24419612| 26898343 |xnCoupon | 50 

|43575857 |24419612| 26898346 |regOption| 139   
|43575858 |24419612| 26898346 |xnCoupon | 50 

我的嘗試是這樣的

Select sum(price) FROM table where type ='regOption' AND (something)檢查是regOption與xnCoupon由同一相關entry_id?

有人可以幫助我的邏輯,任何幫助表示歡迎

+0

有什麼想法嗎?我可以幫你? – vladimirProp

回答

1
SELECT SUM(price) 
FROM table 
WHERE type = 'regOption' 
AND entry_id IN 
(
    SELECT entry_id 
    FROM table 
    WHERE type = 'xnCoupon' 
) 
+0

tnx投了我的問題 – vladimirProp

1

這可能不是你在找什麼 - 這項聲明總結regOption類型與對應的xnCoupon每次交易的價格,並給出了總計。

select ifnull(reg.trans_id,'<<TOTAL>>') as trans_id, 
     sum(reg.price) 
    from `table` reg 
    join `table` xnc 
     on ( xnc.entry_id = reg.entry_id 
      and reg.type = 'regOption' 
      and xnc.type = 'xnCoupon') 
group by reg.trans_id with rollup;