MySQL - 从一个表到2列的2个和2个WHERE语句

时间:2014-10-29 10:29:01

标签: mysql

也许对于某人来说这是一个简单的答案,但我搜索并搜索并失败了。 这是我拥有的:1包含以下内容的表:

id, int
year, int
month, int
day, int
revenue, float
sub_category, text

我想要获得的是1个SQL语句,它返回1个包含3列的表来保存每月收入和sub_category的总和

-------------------------------
| Month | revcomp1 | revcomp2 |
-------------------------------
|   01  | sumcat1  | sumcat2  |
-------------------------------
|   02  | sumcat1  | sumcat2  |
-------------------------------
|   ..  |    ..    |    ..    |

这是我正在运行的SQL语句:

SELECT 
 month,
 cast(sum(rev *-1) as decimal(10,2)) as REVCOMP1,
 0 as REVCOMP2
FROM 
 tbl_data
WHERE
 year='2014' and sub_category='comp1'
GROUP BY month, sub_category DESC

UNION

SELECT 
 month,
 0 as REVCOMP1
 cast(sum(rev *-1) as decimal(10,2)) as REVCOMP2,
FROM 
 tbl_data
WHERE
 year='2014' and sub_category='comp2'
GROUP BY month, sub_category DESC

但是,这并不是真正在一行中返回给定月份的总和......

非常感谢任何帮助, 感谢

1 个答案:

答案 0 :(得分:0)

您可以使用条件聚合执行此操作:

select month,
       cast(sum(case when sub_cateogry = 'comp1' then rev *-1 end) as decimal(10,2)) as REVCOMP1,
       cast(sum(case when sub_category = 'comp2' then rev *-1 end) as decimal(10,2)) as REVCOMP2
from tbl_data t
where year = '2014'
group by month;