0

我有两种类型的 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

谢谢 !

在此处输入图像描述

4

2 回答 2

3

您想要聚合这两个结果:

SELECT day, month, SUM(total)
  FROM ( /* first_query */
        UNION ALL
         /* second_query */)
 GROUP BY day, month
于 2013-03-07T11:22:35.850 回答
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在输出中看到一行(即前两列将用于分组,最后一列将相加)。

于 2013-03-07T11:28:55.563 回答