我有两种类型的sql查询它返回相同的数据,我需要合并其中两个,如果我使用Union 它把第二个结果放到第一个结果但我不需要这个,我需要合并日期或有没有办法将两个SQL查询合并到一个查询?
SELECT TO_CHAR(s.CR_DATE, 'DD') DAY, TO_CHAR(s.CR_DATE, 'MM') MONTH, count(*) total FROM SUSR s
left outer join SUSR_ACCT sa on (s.SUSR_ID = sa.SUSR_ID)
WHERE s.CR_DATE > '01-01-2012' AND s.CR_DATE < '01-01-2014' and sa.ACCT_ID = 123
GROUP BY TO_CHAR(s.CR_DATE, 'DD'), TO_CHAR(s.CR_DATE, 'MM')
SELECT TO_CHAR(s.CR_DATE, 'DD') DAY, TO_CHAR(s.CR_DATE, 'MM') MONTH, count(*) total FROM SUSR s
WHERE s.CR_DATE > '01-01-2012' AND s.CR_DATE < '01-01-2014' and s.APP_ACCT_ID = 123
GROUP BY TO_CHAR(s.CR_DATE, 'DD'), TO_CHAR(s.CR_DATE, 'MM')
ORDER BY month, day
谢谢!
答案 0 :(得分:3)
您想要汇总两个结果:
SELECT day, month, SUM(total)
FROM ( /* first_query */
UNION ALL
/* second_query */)
GROUP BY day, month
答案 1 :(得分:1)
假设我正确理解合并策略背后的意图,您应该添加第二级GROUP BY
,并总计相应的总数,如下所示:
SELECT DAY, MONTH, SUM(total) FROM (
SELECT TO_CHAR(s.CR_DATE, 'DD') DAY, TO_CHAR(s.CR_DATE, 'MM') MONTH, count(*) total
FROM SUSR s
left outer join SUSR_ACCT sa on (s.SUSR_ID = sa.SUSR_ID)
WHERE s.CR_DATE > '01-01-2012' AND s.CR_DATE < '01-01-2014' and sa.ACCT_ID = 123
GROUP BY TO_CHAR(s.CR_DATE, 'DD'), TO_CHAR(s.CR_DATE, 'MM')
UNION ALL
SELECT TO_CHAR(s.CR_DATE, 'DD') DAY, TO_CHAR(s.CR_DATE, 'MM') MONTH, count(*) total
FROM SUSR s
WHERE s.CR_DATE > '01-01-2012' AND s.CR_DATE < '01-01-2014' and s.APP_ACCT_ID = 123
GROUP BY TO_CHAR(s.CR_DATE, 'DD'), TO_CHAR(s.CR_DATE, 'MM')
) src
GROUP BY DAY, MONTH
ORDER BY DAY, MONTH
如果第一个结果中有1 2 5
行,第二个结果中有1 2 4
行,您将在输出中看到1 2 9
行(即前两列将是用于分组,最后一个将总计)。