我已经坚持了很久。这可能是显而易见的事情,但说实话,我没有那么多的SQL知识。我得到了以下两个表:
Date1 Cost1
-------------------
01-01-14 50,65
02-01-14 12,12
和
Date2 Cost2
-------------------
01-01-14 123,12
02-01-14 14,15
我需要关注输出:
Number of month Total amount of table 1 and 2 for that specific month
-------------------------------------------------------------------------
1 2425252,52
2 53252,89
我得到的查询适用于单个表,我可以在我的实际代码中对它们进行排序,但我只知道它可以通过查询但我根本无法找到方法。我一直在关注内部和外部联接,但由于我使用了两个分组语句,因此我得到的结果是每个月的数字乘以12并且值不正确。
提前非常感谢你。
答案 0 :(得分:0)
您可以将结果合并在一起,然后对这些结果求和。请记住,您根据OP过了几年。如果这不是意图,那么我还提供了按年和月分组的替代方案。
按月分组:
SELECT c1.monthNum
, sum(c1.cost) as cost
FROM
(
SELECT to_char(t1.date1, 'MM') as monthNum, SUM(t1.cost1) as cost
FROM table1 t1
WHERE ..your table1 where clause here...
GROUP BY to_char(t1.date1, 'MM')
UNION ALL
SELECT to_char(t2.date1, 'MM') as monthNum, SUM(t2.cost1) as cost
FROM table1 t2
WHERE ..your table2 where clause here...
GROUP BY to_char(t2.date1, 'MM')
) c1
GROUP BY c1.monthNum
或按年份分组:
SELECT c1.yearNum
, c1.monthNum
, sum(c1.cost) as cost
FROM
(
SELECT to_char(t1.date1, 'YYYY') AS yearNum, to_char(t1.date1, 'MM') as monthNum, SUM(t1.cost1) as cost
FROM table1 t1
WHERE ..your table1 where clause here...
GROUP BY to_char(t1.date1, 'YYYY'), to_char(t1.date1, 'MM')
UNION ALL
SELECT to_char(t2.date1, 'YYYY') AS yearNum, to_char(t2.date1, 'MM') as monthNum, SUM(t2.cost1) as cost
FROM table1 t2
WHERE ..your table2 where clause here...
GROUP BY to_char(t2.date1, 'YYYY'), to_char(t2.date1, 'MM')
) c1
GROUP BY c1.yearNum, c1.monthNum