如何在没有工会30次的情况下重复过去30天的查询?

时间:2015-06-19 23:39:32

标签: oracle

我有一个返回今天(sysdate)值的查询但是在没有创建30个单独的查询的情况下重复查询过去30天的最佳方法是什么?

例如,这里是基本查询:

SELECT sum(duration)/3600
FROM IGN_OEE_EVENTS_D 
where asset_id = 1978 and event_type = 1 and shift = 2 and trunc(event_dt)=trunc(sysdate)

我想避免的是重复这样的查询:

SELECT sum(duration)/3600
FROM IGN_OEE_EVENTS_D 
where asset_id = 1978 and event_type = 1 and shift = 2 and trunc(event_dt)=trunc(sysdate)
union
SELECT sum(duration)/3600
FROM IGN_OEE_EVENTS_D 
where asset_id = 1978 and event_type = 1 and shift = 2 and trunc(event_dt)=trunc(sysdate)-1
union
SELECT sum(duration)/3600
FROM IGN_OEE_EVENTS_D 
where asset_id = 1978 and event_type = 1 and shift = 2 and trunc(event_dt)=trunc(sysdate)-2
union
SELECT sum(duration)/3600
FROM IGN_OEE_EVENTS_D 
where asset_id = 1978 and event_type = 1 and shift = 2 and trunc(event_dt)=trunc(sysdate)-3

有没有办法做这样的事情?

REPEAT all dates where event_dt between sysdate and sysdate -30
SELECT sum(duration)/3600
FROM IGN_OEE_EVENTS_D 
where asset_id = 1978 and event_type = 1 and shift = 2 
谢谢。

1 个答案:

答案 0 :(得分:1)

听起来你只需要GROUP BY。我猜你还想要ORDER BY

SELECT trunc(event_dt), sum(duration)/3600
  FROM IGN_OEE_EVENTS_D 
 where asset_id = 1978 
   and event_type = 1 
   and shift = 2 
   and trunc(event_dt) >= trunc(sysdate)-30
 group by trunc(event_dt)
 order by trunc(event_dt)