一起加入两个MYSQL WHERE查询

时间:2015-12-10 09:53:55

标签: mysql

我想加入2个查询的结果,以便最终得到3列,第一列是MONTH,第二列是WITHDRAWALS,第三列是DEPOSITS。

查询1:

SELECT
    DATE_FORMAT(Time, "%m-%Y") AS MONTH,
    SUM(Profit_Loss) AS DEPOSITS
FROM
    `deposits_withdrawals_view`
WHERE
    Summary = 'Cash In'
GROUP BY
    DATE_FORMAT(Time, "%m-%Y")

查询2:

SELECT
    DATE_FORMAT(Time, "%m-%Y") AS MONTH,
    SUM(Profit_Loss) AS WITHDRAWALS
FROM
    `deposits_withdrawals_view`
WHERE
    Summary = 'Cash Out'
GROUP BY
    DATE_FORMAT(Time, "%m-%Y")

两者都是单独工作但如何在1个查询中将它们连接在一起?

感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

您可以为此

执行条件聚合
select
DATE_FORMAT(Time, "%m-%Y") AS MONTH,
sum(case when Summary='Cash In' then Profit_Loss else 0 end) as DEPOSITS,
sum(case when Summary='Cash Out' then Profit_Loss else 0 end) as WITHDRAWALS
FROM
    `deposits_withdrawals_view`
GROUP BY MONTH

答案 1 :(得分:0)

如果你想横向加入,你可以这样做:

 select * from (SELECT
    DATE_FORMAT(Time, "%m-%Y") AS MONTH,
    SUM(Profit_Loss) AS DEPOSITS
FROM
    `deposits_withdrawals_view`
WHERE
    Summary = 'Cash In'
GROUP BY
    DATE_FORMAT(Time, "%m-%Y")) t1
INNER JOIN (SELECT
    DATE_FORMAT(Time, "%m-%Y") AS MONTH,
    SUM(Profit_Loss) AS WITHDRAWALS
FROM
    `deposits_withdrawals_view`
WHERE
    Summary = 'Cash Out'
GROUP BY
    DATE_FORMAT(Time, "%m-%Y")) as t2
ON t1.column1 = t2.column1

其中column1是join(外键)

中使用的字段

如果你想垂直加入

SELECT
    DATE_FORMAT(Time, "%m-%Y") AS MONTH,
    SUM(Profit_Loss) AS DEPOSITS
FROM
    `deposits_withdrawals_view`
WHERE
    Summary = 'Cash In'
GROUP BY
    DATE_FORMAT(Time, "%m-%Y")

union all 

SELECT
    DATE_FORMAT(Time, "%m-%Y") AS MONTH,
    SUM(Profit_Loss) AS WITHDRAWALS
FROM
    `deposits_withdrawals_view`
WHERE
    Summary = 'Cash Out'
GROUP BY
    DATE_FORMAT(Time, "%m-%Y")

你也可以用union替换union all,其中union删除重复的行

答案 2 :(得分:0)

试试这个

SELECT
DATE_FORMAT(Time, "%m-%Y") AS MONTH,
SUM(Profit_Loss) AS DEPOSITS,(SELECT
SUM(Profit_Loss) 
FROM
deposits_withdrawals_view WHERE Summary = 'Cash Out' 
GROUP BY DATE_FORMAT(Time, "%m-%Y")) AS WITHDRAWALS 
FROM deposits_withdrawals_view WHERE Summary = 'Cash In' 
GROUP BY DATE_FORMAT(Time, "%m-%Y")