Wednesday, July 28, 2010

Generate Sequence

This query generates the same number '1' 10 times.
SELECT 1
FROM DUAL
CONNECT BY LEVEL <= 10;


This query generates a sequence of number from 1 to 31.
SELECT ROWNUM FROM
(
SELECT 1
FROM Dual
GROUP BY CUBE (2, 2, 2, 2, 2)
)
WHERE ROWNUM <= 31;

This query can be used to generate a sequence of date from 20100201 to 20100228
SELECT TRUNC(TO_DATE('20100201','yyyymmdd'),'MM')+ROWNUM -1 DATES FROM
(
SELECT 1
FROM Dual
GROUP BY CUBE (2, 2, 2, 2, 2)
)
WHERE ROWNUM <= ADD_MONTHS(TRUNC(TO_DATE('20100201','YYYYMMDD'),'MM'),1) - TRUNC(TO_DATE('20100201','YYYYMMDD'),'MM');

By generating this sequence of dates or numbers you can join to another table to see if any data exists for these numbers or dates.For example below I wanted to find if there were any records in a very big table if data existed for certain dates. I could have done a distinct but i chose this method.
select d.*,c.* from

(
SELECT TRUNC(TO_DATE('20100201','yyyymmdd'),'MM')+ROWNUM -1 DATES FROM
(
SELECT 1
FROM Dual
GROUP BY CUBE (2, 2, 2, 2, 2)
)
WHERE ROWNUM <= ADD_MONTHS(TRUNC(TO_DATE('20100201','YYYYMMDD'),'MM'),1) - TRUNC(TO_DATE('20100201','YYYYMMDD'),'MM')
) d left outer join  eim_split_skill c on d.dates = c.current_date
-- where upper(split_skill)='GENERAL'
order by dates;

No comments:

Post a Comment