2017-04-14 54 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;