MYSQL选择查询我希望在哪里条件的两行

时间:2016-10-10 10:50:57

标签: php mysql

/* First query */
SELECT YEAR, SUM( amount ) AS total
FROM accounts
WHERE ((MONTH >=  '10' || 
        MONTH <=  '12' && YEAR =  '2015') && 
       (MONTH >=  '1' || 
        MONTH <=  '3' && YEAR =  '2016' ))
GROUP BY YEAR

/* Second query */
SELECT YEAR, SUM( amount ) AS total
FROM accounts
WHERE ((MONTH >= '1' || 
        MONTH <= '3' && YEAR = '2015') &&
       (MONTH >= '5' || 
        MONTH <= '10' && YEAR = '2015'))
GROUP BY YEAR

第一个查询根据年份返回两行。但第二个查询只返回一行。

我知道我是按照年份分组完成的,但是我想要两行来完成我的两个条件匹配。

还有其他建议吗?

这是输出。

output1 output2

1 个答案:

答案 0 :(得分:1)

检查方式: -

SELECT YEAR, SUM( amount ) AS total
FROM accounts
WHERE (((MONTH >=  '1' || MONTH <=  '3') && YEAR =  '2015') ||
((MONTH >=  '5' || MONTH <=  '10') && YEAR =  '2015'))
GROUP BY YEAR

OR

SELECT YEAR, SUM( amount ) AS total
FROM accounts
WHERE (MONTH >=  '1' || MONTH <=  '3') && YEAR =  '2015' 
GROUP BY YEAR
Union all
SELECT YEAR, SUM( amount ) AS total
FROM accounts
WHERE (MONTH >=  '5' || MONTH <=  '10') && YEAR =  '2015' 
GROUP BY YEAR