我试图检索2015年每小时的平均交易量"从SQL Server和我使用以下查询:
select
avg(Cast(a.Orders as float)) as AvgOrders, a.Hour
from
(select
count(*) as Orders,
datepart(hour,created) as Hour,
datepart(day,created) as Day
from
ORDERS
where
-- datepart(month,created) = 1
datepart(year,created) = 2015
and DATENAME(dw, created) NOT IN ('Saturday', 'Sunday')
and branchno in ('113', '120', '122')
and (filing = 1 or delivery = 1)
group by
datepart(hour, created),
datepart(day, created)
) a
group by
a.Hour
order by
a.Hour
此查询为我提供了每小时数据,这似乎是不正确的(每小时约150次交易,我知道这是不正确的)。当我取消注释语句datepart(month, created) = 1
并使用其中的任何月份时,数据接近每小时40个事务,这是正确的数据。
为什么我无法为整个2015年生成正确的数据?为什么在选择月度数据时会获得准确的数据?
任何帮助都将受到高度赞赏。
答案 0 :(得分:0)
尝试这样的事情,在发生的那一天分别获得每小时。
select count(*) as Orders
, cast(created as date) as Date
, Datepart(hour, created) as Hour
from ORDERS
group by cast(created as date)
, Datepart(hour, created)
order by Date, Hour