在使用动态日期范围进行数据透视查询时寻求帮助

时间:2018-07-05 18:06:38

标签: sql oracle date dynamic pivot

我有查询1,该查询返回一周中的7个日期,该日期从星期六开始,到星期五结束。

$1,000 - Good!
$1.000 - Bad, should have been $1,000
$1,000.000 - Bad, should have been $1,000,000
$1,000.000.00 - Bad, should have been $1,000,000.00
$1.000.000,00 - Bad, should have been $1,000,000.00
$10,.000 - Bad, should have been $10,000
500.000 - Bad, should have been 500,000
1.325% - Good!

查询二是一个枢轴查询,该查询现在可以使用硬编码日期正常工作。我怎样才能使枢轴((.....)中insrt的总和(count))动态化?您现在看到它是硬编码的。谢谢

 SELECT TRUNC(to_date('08-Jul-2018', 'dd-Mon-yyyy'), 'IW') 
      + Level - (1+ TRUNC(to_date('08-Jul-2018', 'dd-Mon-yyyy'), 'IW') 
      - TRUNC(to_date('08-Jul-2018', 'dd-Mon-yyyy'), 'IW'))
   FROM dual
CONNECT BY level <= 8; --great

1 个答案:

答案 0 :(得分:0)

select trunc(to_date('04-JUL-2018', 'dd-Mon-yyyy'), 'IW') + level -1
from dual
connect by level < 7;
--Query 2
WITH t AS
  ( SELECT DISTINCT test_number,
    TO_CHAR(insrt_dttm,'mm-dd-yyyy') AS date_without_time,
    rec_cnt
  from cdw_t.data_monitoring_result
  WHERE TRUNC(insrt_dttm) >= to_date('01-01-1900', 'MM-DD-YYYY')
  AND TRUNC(insrt_dttm)   <= to_date('12-31-4000', 'MM-DD-YYYY')
  )

SELECT                                             *
FROM t pivot ( SUM(rec_cnt) FOR date_without_time IN ('06-30-2018','07-01-2018','07-02-2018','07-03-2018','07-04-2018','07-05-2018','07-06-2018')) ;
TEST_NUMBER '06-30-2018'    '07-01-2018'    '07-02-2018'    '07-03-2018'    '07-04-2018'    '07-05-2018'    '07-06-2018'
51  10  10  10  11  14  14  14                  
1   179 179 179 179 179 179 179
30  127 127 127 127 127 127 127
53  594 594 594 594 594 594 226

Above is the sample output.  I was hoping that maybe I can use query 1 replace the hard coded dates in the FOR statement brackets.   I don't know how to write PL/SQL and not sure if it is possible to have a dynamic range inside the pivot for statement.