使用WITH AS后获取重复记录

时间:2019-08-06 06:08:25

标签: sql oracle common-table-expression

我有三个选择查询,它们按小时显示了月的最后一天(当前,当前-1,当前-2)的记录计数。

我正在尝试使所有三个输出并排的单个查询。

我已经使用with as来完成这项工作。

问题正在获取重复的记录(近2k条记录),其中预期的最大行数为24(每天24小时)。

查询:

with curr as 
(
  Select
    last_day(add_months(trunc(sysdate, 'mm'), 0)),
    TO_CHAR(created_date, 'HH24') as "Time",
    count(1) as "Count"
  from
    table1
  where cretd_date >= trunc(last_day(add_months(trunc(sysdate, 'mm'), 0)))
  group by
    TO_CHAR(created_date, 'HH24'),
    last_day(add_months(trunc(sysdate, 'mm'), 0))
  order by
    TO_CHAR(cretd_date, 'HH24')
),
curr_1 as 
(
  Select
    last_day(add_months(trunc(sysdate, 'mm'), -1)),
    TO_CHAR(created_date, 'HH24') as "Time",
    count(1) as "Count"
  from
    table1
  where cretd_date >= trunc(last_day(add_months(trunc(sysdate, 'mm'), -1)))
  group by
    TO_CHAR(created_date, 'HH24'),
    last_day(add_months(trunc(sysdate, 'mm'), -1))
  order by
    TO_CHAR(cretd_date, 'HH24')
),
curr_2 as
(
  Select
    last_day(add_months(trunc(sysdate, 'mm'), -2)),
    TO_CHAR(created_date, 'HH24') as "Time",
    count(1) as "Count"
  from
    table1
  where cretd_date >= trunc(last_day(add_months(trunc(sysdate, 'mm'), -2)))
  group by
    TO_CHAR(created_date, 'HH24'),
    last_day(add_months(trunc(sysdate, 'mm'), -2))
  order by
    TO_CHAR(cretd_date, 'HH24')
)
select * from curr, curr_1,curr_2;

实际输出:

2k repeated rows

预期输出:

max 24 rows

last_date  | time   | count   | last_date  | time_1 | count_1 | last_date | time_2| count_2 |
31-july-19 | 00     | 2       | 31-June-19 | 00     | 1       | 31-May-19 | 00    | 3       |
...
31-july-19 | 23     | 34      | 31-June-19 | 23     | 23      | 31-May-19 | 23    | 32      | 

*如果还有其他实现此目标的最佳方法,请分享。

2 个答案:

答案 0 :(得分:2)

我假设您想调整每月结果,可以使用条件汇总。

SELECT TO_CHAR(created_date, 'HH24') AS "Time"
    ,last_day(sysdate) AS m1
    ,last_day(add_months(sysdate, - 1)) m2
    ,last_day(add_months(sysdate, - 2)) m3
    ,count(CASE 
            WHEN created_date >= trunc(last_day(sysdate))
                THEN 1
            END) m1_count
    ,count(CASE 
            WHEN created_date >= trunc(last_day(add_months(sysdate, - 1)))
                THEN 1
            END) m2_count
    ,count(CASE 
            WHEN created_date >= trunc(last_day(add_months(sysdate, - 2)))
                THEN 1
            END) m3_count
FROM table1
GROUP BY TO_CHAR(created_date, 'HH24')
ORDER BY "Time";

注意:由于您尚未提供数据,因此这是未经测试的查询。请尝试让我知道。

答案 1 :(得分:0)

您缺少CURR, CURR_1, CURR_2之间的联接。

加入应基于"Time"列。

所以您的SELECT查询应该是这样的:

SELECT
    *
FROM
    CURR JOIN
    CURR_1 USING("Time") JOIN
    CURR_2 USING("Time");

干杯!