【问题标题】:Hourly erroneous data retrieved from SQL Server从 SQL Server 检索的每小时错误数据
【发布时间】:2015-08-03 16:23:49
【问题描述】:

我正在尝试从 SQL Server 检索“2015 年每小时平均事务数”,并且我正在使用以下查询:

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 年生成正确的数据?为什么选择月度数据会得到准确的数据?

任何帮助将不胜感激。

【问题讨论】:

  • 第 1 天存在于所有月份中,因此它将所有月份归为这一天。您还需要按月和年分组。
  • 是的,我刚刚想通了,非常感谢。

标签: sql-server


【解决方案1】:

尝试这样的方法,按发生的那一天分别获取每个小时。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 2011-11-05
    • 1970-01-01
    相关资源
    最近更新 更多