如何结合两个mysql查询

时间:2014-12-05 09:41:44

标签: mysql sql

我想将这两个查询与两个队长结合起来应该是平等的:

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

3 个答案:

答案 0 :(得分:0)

组合可以是 JOIN UNION

加入

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

对于 UNION

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 

答案 1 :(得分: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

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

答案 2 :(得分: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 

子查询只会返回captain_name payment_modecardcash的{​​{1}}。然后按captain_name选择group bycaptain_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只表示两个查询返回的队长,应该通过组合查询返回。