2013-07-20 237 views
1

我的SQL Server 2012上工作下面的查詢給我的價值觀的每小時平均在CounterValue列:每小時平均

select 
    dateadd(hour, datediff(hour, 0, CounterDateTime), 0), 
    avg(CounterValue) 
from mopsxactthroughput 
group by 
    dateadd(hour, datediff(hour, 0, CounterDateTime), 0) 

我想,如果如果只有一條匹配那個小時的記錄,那麼修改它以便它在一小時內不返回任何行。例如,如果在2013-06-06T20:00:00和2013-06-06T21:00:00之間只有一條記錄,那麼我希望在那一小時內沒有任何行返回。

它讓我覺得有點多,要求SELECT,但也許有一種方法。 (我的回退將返回按小時分組的所有記錄,然後遍歷該行給自己設定了在Java和應用平均化處理/丟棄在那裏)

+0

加上'HAVING COUNT(*)> 1'或者'HAVING COUNT(CASE WHEN CounterDateTime BETWEEN '2013-06-06T20:00:00' 與 '2013-06-06T21:00:00' THEN 1 END)> 1' –

回答

2

只需添加一個having條款:

select 
    dateadd(hour, datediff(hour, 0, CounterDateTime), 0), 
    avg(CounterValue) 
from mopsxactthroughput 
group by 
    dateadd(hour, datediff(hour, 0, CounterDateTime), 0) 
having count(*) > 1 
1

也許這CTE工程:

with cte as( 
    select dateadd(hour, datediff(hour, 0, CounterDateTime), 0) as Hour, 
      avg(CounterValue)over(partition by dateadd(hour, datediff(hour, 0, CounterDateTime), 0)) as AvgCounter, 
      Count(*)over(partition by dateadd(hour, datediff(hour, 0, CounterDateTime), 0)) as HourCount, 
      CounterValue, 
      CounterDateTime 
    from mopsxactthroughput 
) 
select Hour, CounterValue, CounterDateTime, AvgCounter 
from cte 
where HourCount > 1 
+0

看起來它是個伎倆。我必須梳理結果,以確保我會接受你的答案,謝謝。 –