Oracle query to return each half hour values

时间:2015-06-25 19:09:59

标签: sql oracle

While I am running this query I get the data showing the time for which i have records. I also wanted to see zeros for the time I don't have data.. SELECT x.TIMESLOT AS "FROM", SUM(x.VALUE) AS x.VALUE FROM (SELECT TO_CHAR (dd.create_dt, 'HH24') || DECODE (SIGN (TO_CHAR (dd.create_dt, 'MI') - 30),-1, '01','31') AS TIMESLOT, COUNT(*) AS VALUE FROM deposits LEFT JOIN d_user u ON u.ID = dd.USER_ID WHERE dd.create_dt BETWEEN :p_from_dt AND :p_to_dt AND dd.ACTIVE_IND = 'Y' GROUP BY TO_CHAR (dd.create_dt, 'HH24') || DECODE (SIGN (TO_CHAR (dd.create_dt, 'MI') - 30),-1, '01','31') UNION ALL SELECT TO_CHAR (wd.create_dt, 'HH24') || DECODE (SIGN (TO_CHAR (wd.create_dt, 'MI') - 30), -1, '01', '31') AS TIMESLOT, COUNT(*) AS VALUE FROM wages wd WHERE wd.create_dt BETWEEN :p_from_dt AND :p_to_dt GROUP BY TO_CHAR (wd.create_dt, 'HH24') || DECODE (SIGN (TO_CHAR (wd.create_dt, 'MI') - 30), -1, '01','31')) x GROUP BY x.TIMESLOT ORDER BY x.TIMESLOT OUTPUT FROM VALUE 0731 9 1101 7 1331 8 1401 9 1431 3 1631 1 I am trying to get out put as fallows OUTPUT FROM VALUE 0601 0 0631 0 0701 0 0731 9 0801 0 0831 0 0901 0 0931 0 1001 0 1031 0 1101 7 1131 0 1201 0 1231 0 1301 0 1331 8 1401 9 1431 3 1501 0 1531 0 1601 0 1631 1 1701 0 1731 0 1801 0 1831 0 1901 0 1931 0 2001 0 2031 0 2101 0 2131 0 2201 0

1 个答案:

答案 0 :(得分:1)

您可以使用查询生成所有半小时间隔的列表:

SELECT TO_CHAR( TO_DATE( '0601', 'HH24MI' ) + (LEVEL - 1)/48, 'HH24MI' ) AS timeslot
FROM   DUAL
CONNECT BY
       LEVEL <= 33;

然后,您可以使用LEFT OUTER JOIN将其添加到查询中;像这样的东西:

WITH half_hours AS (
  SELECT TO_CHAR( TO_DATE( '0601', 'HH24MI' ) + (LEVEL - 1)/48, 'HH24MI' ) AS timeslot
  FROM   DUAL
  CONNECT BY
         LEVEL <= 33
), data AS (
  <your_query>
)
SELECT h.timeslot,
       COALESCE( d.value, 0 ) AS value
FROM   half_hours h
       LEFT OUTER JOIN data d
       ON h.timeslot = d.timeslot;