我试图在枢轴的帮助下找到平均值,但无法找到正确的解决方案。
以下是我的疑问:
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
我原来的表是:
以上查询的结果是:
预期结果:
对于15分钟间隔查询,请参考我原来的帖子:
Group data by interval of 15 minutes and use cross tab
答案 0 :(得分:0)
SQL Server对整数执行整数运算操作。问题是这是一个整数:
sum(b.ordercount) as ordercounts
(推测)。
因此,只需将其转换为浮动/固定点数即可。我通常只乘以1.0:
sum(b.ordercount)*1.0 as ordercounts
但如果您愿意,可以更具体地说明您的类型。
答案 1 :(得分:0)
尝试施放以浮动 -
AVG(CAST(ordercounts AS FLOAT))
SUM(CAST(b.ordercount AS FLOAT)) AS ordercounts
答案 2 :(得分: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起有效。 在这个例子中,我只使用了一个间隔,但你可以将它扩展到你需要的所有间隔。
我尝试了昨天的答案中的一些样本数据,它返回的值如下:
快乐的编码! :)