2017-07-18 23 views
0

我試圖在數據透視的幫助下找到平均值,但無法找到正確的解決方案。以數據爲中心計算平均值

下面是我的查詢:

select branch, ISNULL([11:00], 0) as [11:00],ISNULL([11:15], 0) as 
[11:15],ISNULL([11:30], 0) as [11:30], ISNULL([11:45], 0) as [11:45], 
ISNULL([12:00], 0) as [12:00] 

from 
( 
select b.branchname 
     ,convert(varchar(5), intervals.interval_start_time, 108) 
     ,sum(b.ordercount) ordercounts 
from branch b cross apply dbo.getDate15MinInterval(CAST(b.TransactionDate 
as date)) as intervals 
where b.TransactionDate >= interval_start_time and b.TransactionDate <= 
interval_end_time 
and CAST(TransactionDate AS date) IN ('2017-07-01','2017-07-08') 

group by DATEPART(WEEKDAY,TransactionDate),b.branchname,intervals.interval_start_time,intervals.interval_end_time 
) t 
pivot (avg(ordercounts) for interval_start_time in ([11:00], [11:15] , 
[11:30], [11:45], [12:00])) as p 

我原來的表是:從上面的查詢

enter image description here

結果是:

enter image description here

預期的結果:

enter image description here

對於15minuteinterval查詢,請參考我原來的職位:
Group data by interval of 15 minutes and use cross tab

回答

0

SQL Server會在整數整數算術運算。的問題是,這是一個整數:

sum(b.ordercount) as ordercounts 

(推測)。

所以,只要把它變成浮動/固定點數。我通常只是乘以1.0:

sum(b.ordercount)*1.0 as ordercounts 

但是,如果你喜歡,你可以更具體地說明你的類型。

+0

嗨戈登,那只是漂浮的作品。但是我仍然在輸出中得到1和8。它應該是0.5和4。 – Shivang

0

儘量鑄造浮動 -

AVG(CAST(ordercounts AS FLOAT)) 

SUM(CAST(b.ordercount AS FLOAT)) AS ordercounts 
0

可以做這樣的:

select branchname, [dayname], ISNULL([11:00], 0) as [11:00], AVG(CAST([11:00] as float)) over() [Avg_11:00] 
from 
(
    select branchname, [dayname], ISNULL([11:00], 0) as [11:00], ISNULL([11:15], 0) as [13:15], ISNULL([11:30], 0) as [11:30], ISNULL([11:45], 0) as [11:45] 
    from 
    ( 
     select intervals.[dayname] 
      , b.branchname 
      , convert(varchar(5), intervals.interval_start_time, 108) interval_start_time -- for hh:mm format 
      , sum(b.ordercount) ordercount 
     from branch b cross apply dbo.getDate15MinIntervals(CAST(b.TransactionDate as date)) as intervals 
     where b.transactiondate between interval_start_time and interval_end_time 
     group by intervals.[dayname], b.branchname, intervals.interval_start_time, intervals.interval_end_time 
    ) t 
    pivot (sum(ordercount) for interval_start_time in ([11:00], [11:15] , [11:30], [11:45])) as p 
) t 
group by branchname, [dayname], [11:00] 

AVG OVER()是與SQL Server 2008 在這個例子中,我只用一個區間有效,但你可以將它擴展到所有你需要的。

我試着用一些樣本數據,從昨天的答案,它如下返回值:

enter image description here

編碼愉快! :)