如何优化我的oracle sql?

时间:2017-07-14 03:29:05

标签: sql oracle conditional-aggregation

我需要计算范围两个日期,这个sql是工作,bug不是更好,你能帮助我吗?

select dmc.doctor_id,
(
    select count(*)
    from hele_dct_member_config dmc
    WHERE (EXTRACT(YEAR FROM dmc.start_time) = 2016 OR EXTRACT(YEAR FROM dmc.end_time) = 2016) AND dmc.status=1
    AND TO_DATE('2016-01-31', 'yyyy-mm-dd') BETWEEN start_time AND end_time
) Jan,
(
    select count(*)
    from hele_dct_member_config dmc
    WHERE (EXTRACT(YEAR FROM dmc.start_time) = 2016 OR EXTRACT(YEAR FROM dmc.end_time) = 2016) AND dmc.status=1
    AND TO_DATE('2016-02-28', 'yyyy-mm-dd') BETWEEN start_time AND end_time
) Feb,
.
.
.
from hele_dct_member_config dmc
enter code here
WHERE (EXTRACT(YEAR FROM dmc.start_time) = 2016 OR EXTRACT(YEAR FROM dmc.end_time) = 2016) AND dmc.status=1
grouy by dmc.doctor_id

我需要计算范围两个日期,这个sql是工作,bug不是更好,你能帮助我吗?

2 个答案:

答案 0 :(得分:1)

使用条件聚合:

select dmc.doctor_id,
       sum(case when date '2016-01-31' BETWEEN start_time AND end_time then 1 else 0
           end) as Jan,
       sum(case when date '2016-02-31' BETWEEN start_time AND end_time then 1 else 0
           end) as Feb,
    .
    .
    .
from hele_dct_member_config dmc
where (extract(year from dmc.start_time) = 2016 or
       extract(year from dmc.end_time) = 2016) AND
      dmc.status = 1
group by dmc.doctor_id;

答案 1 :(得分:0)

如果我想得到季度计数?这是一种方式

   SUM(case when date '2016-01-31' BETWEEN start_time AND end_time then 1 else 0 end) + 
   SUM(case when date '2016-02-28' BETWEEN start_time AND end_time then 1 else 0 end) + 
   SUM(case when date '2016-03-31' BETWEEN start_time AND end_time then 1 else 0 end)  one