2014-12-05 95 views
1

我想這兩個查詢有兩個隊長相結合應該是平等的:如何合併兩個MySQL查詢

select distinct(captain_name),sum(finaldiscount) as tot,payment_mode 
from order_master 
where payment_mode='card' 
group by captain_name 

select distinct(captain_name),sum(finaldiscount) as tot,payment_mode 
from order_master 
where payment_mode='cash' 
group by captain_name 
+0

爲什麼要組合相同的查詢?我沒有看到查詢之間的區別。 – 2014-12-05 10:02:12

+0

這兩個查詢看起來都是一樣的 – 2014-12-05 10:02:30

+0

它被錯誤地編輯了,在第一個查詢中有'payment_mode ='card''。 – 2014-12-05 10:04:02

回答

0

結合可以是JOINUNION

對於JOIN

Select * 
from 
(select distinct(captain_name) capName,sum(finaldiscount) as tot,payment_mode from order_master where payment_mode='card' group by captain_name) t1 
INNER JOIN 
(select distinct(captain_name) capName,sum(finaldiscount) as tot,payment_mode from order_master where payment_mode='cash' group by captain_name) t2 on t1.capName = t2.capName 

對於聯合國ION

Select * 
    from 
    (select distinct(captain_name) capName,sum(finaldiscount) as tot,payment_mode from order_master where payment_mode='card' group by captain_name) t1 
    UNION 
    (select distinct(captain_name) capName,sum(finaldiscount) as tot,payment_mode from order_master where payment_mode='cash' group by captain_name) t2 
0

試試這個:

SELECT captain_name, 
     SUM(CASE WHEN payment_mode = 'cash' THEN finaldiscount ELSE 0 END) AS cashTotal, 
     SUM(CASE WHEN payment_mode = 'card' THEN finaldiscount ELSE 0 END) AS cardTotal 
FROM order_master 
WHERE payment_mode IN ('cash', 'card') 
GROUP BY captain_name 

OR

SELECT captain_name, payment_mode, SUM(finaldiscount) total 
FROM order_master 
WHERE payment_mode IN ('cash', 'card') 
GROUP BY captain_name, payment_mode 
0

試試這個:

SELECT captain_name, 
     Sum(finaldiscount) AS tot, 
     payment_mode 
FROM order_master 
WHERE payment_mode IN('cash', 'card') 
     AND captain_name IN (SELECT captain_name 
          FROM order_master 
          WHERE payment_mode IN('cash', 'card') 
          GROUP BY captain_name 
          HAVING Count(DISTINCT payment_mode) = 2) 
GROUP BY captain_name,payment_mode 

子查詢將返回唯一的日其中有payment_mode,即cardcash。然後選擇captain_namegroup by那些行,按captain_name,payment_mode

,如果你不想單獨的行爲cardcash然後使用此:

SELECT captain_name,SUM(finaldiscount) 
FROM order_master 
WHERE payment_mode IN('cash', 'card') 
GROUP BY captain_name 
HAVING Count(DISTINCT payment_mode) = 2 

注:我認爲two captain should be equal意味着只有那些被兩個查詢返回的隊長,應當由合併返回查詢。