My query is
select ENTRIES, SUM( CASE WHEN to_char(to_date(record_date, 'yyyy/mm/dd'),'YYYY') =2020 THEN ENTRIES END ) AS "Curr Yr ENTRIES" , SUM( CASE WHEN to_char(to_date(record_date, 'yyyy/mm/dd'),'YYYY') =2019 THEN ENTRIES END ) AS "PREV Yr ENTRIES" , SUM( CASE WHEN to_char(to_date(record_date, 'yyyy/mm/dd'),'MM') =11 THEN ENTRIES END ) AS "Current Month ENTRIES" , SUM( CASE WHEN to_char(to_date(record_date, 'yyyy/mm/dd'),'MM') =10 THEN ENTRIES END ) AS "PREV Month ENTRIES" , SUM( CASE WHEN to_char(to_date(record_date, 'yyyy/mm/dd'),'MM') =09 THEN ENTRIES END ) AS "PREV TO PREV Month ENTRIES" , SUM( CASE WHEN to_char(to_date(record_date,'yyyy/mm/dd'), 'Q')=4 THEN ENTRIES END ) AS "Curr Qtr ENTRIES" , SUM( CASE WHEN to_char(to_date(record_date,'yyyy/mm/dd'), 'Q')=3 THEN ENTRIES END ) AS "PREV Qtr ENTRIES" from market group by ENTRIES
Im new to oracle and in my query i have hard coded the values of year ,month and quarter. But i want my query to work without giving any value so that it automatically picks value let me know how can it be done.
Advertisement
Answer
You can use:
SELECT ENTRIES, SUM( CASE WHEN record_date >= TRUNC( SYSDATE, 'YYYY' ) AND record_date < ADD_MONTHS( TRUNC( SYSDATE, 'YYYY' ), 12 ) THEN ENTRIES END ) AS "Curr Yr ENTRIES", SUM( CASE WHEN record_date >= ADD_MONTHS( TRUNC( SYSDATE, 'YYYY' ), -12 ) AND record_date < TRUNC( SYSDATE, 'YYYY' ) THEN ENTRIES END ) AS "Prev Yr ENTRIES", SUM( CASE WHEN record_date >= TRUNC( SYSDATE, 'MM' ) AND record_date < ADD_MONTHS( TRUNC( SYSDATE, 'MM' ), 1 ) THEN ENTRIES END ) AS "Curr Month ENTRIES", SUM( CASE WHEN record_date >= ADD_MONTHS( TRUNC( SYSDATE, 'MM' ), -1 ) AND record_date < TRUNC( SYSDATE, 'MM' ) THEN ENTRIES END ) AS "Prev Month ENTRIES", SUM( CASE WHEN record_date >= TRUNC( SYSDATE, 'Q' ) AND record_date < ADD_MONTHS( TRUNC( SYSDATE, 'Q' ), 3 ) THEN ENTRIES END ) AS "Curr Qtr ENTRIES", SUM( CASE WHEN record_date >= ADD_MONTHS( TRUNC( SYSDATE, 'Q' ), -3 ) AND record_date < TRUNC( SYSDATE, 'Q' ) THEN ENTRIES END ) AS "Prev Qtr ENTRIES" from market group by ENTRIES
(Although I’m not convinced you want the initial ENTRIES,
in the SELECT
clause or the final GROUP BY
and, instead, could just SUM
over the entire period.)