尝试循环查询以获取每月计数

时间:2019-06-25 19:43:23

标签: sql oracle

我需要获取每月每个程序包有效覆盖的员工数量。跨度为50个月,所以不想运行50次。我需要在这些日期之间的每个月的最后一天使用每种包装的人数

我确定我可以编写一个循环来检查每个日期,但是我一生无法弄清楚。

SELECT COUNT (DISTINCT t.employee_num)
       ,t.PACKAGE
FROM TTABLE2 t
WHERE '&AS_OF' BETWEEN t.from_date AND t.to_date
GROUP BY 
       t.PACKAGE
AS_OF_DATE  BENEFIT Employee_NUM    FROM_DATE   TO_DATE
2015-04-30  Life    000009595   2015-04-01  2015-12-31
2015-04-30  Health  000009595   2015-04-01  2016-03-31
2015-04-30  Life    000009983   2015-04-01  2015-12-31
2015-04-30  Life    000011066   2015-04-01  2015-12-31
2015-04-30  Health  000011066   2015-04-01  2016-03-31
2015-04-30  Life    000011093   2015-04-01  2015-12-31
2015-04-30  Health  000011093   2015-04-01  2016-03-31
2015-04-30  Life    000011100   2015-04-01  2015-12-31
2015-04-30  Health  000011100   2015-04-01  2016-03-31

1 个答案:

答案 0 :(得分:0)

SELECT   d.as_of_date, 
         Benefit COUNT(DISTINCT employee_number)
FROM     ttable2 t
JOIN     (SELECT     LAST_DAY(ADD_MONTHS(fd, LEVEL)) AS as_of_date
          FROM       (SELECT MIN(from_date) AS fd, MAX(to_date) AS td
                      FROM   ttable2)
          CONNECT BY LAST_DAY(ADD_MONTHS(fd, LEVEL)) < td) d ON 
         D.as_of_date BETWEEN t.from_date AND t.to_date
GROUP BY d.as_of_date, PACKAGE

您可以使用connect by语法在每个月的适当范围内生成一系列的最后几天,然后将其加入不同数量的员工人数:

SELECT   as_of_date, package, COUNT(DISTINCT employee_num)
FROM     ttable2 t
JOIN     (SELECT     LAST_DAY(ADD_MONTH(fd, LEVEL)) AS as_of_date
          FROM       (SELECT MIN(from_date) AS fd, MAX(to_date) AS td
                      FROM   ttable2)
          CONNECT BY LAST_DAY(ADD_MONTH(fd, LEVEL)) < td) d ON 
         s.as_of_date BETWEEN t.from_date AND t.to_date
GROUP BY as_of_date, pacakge