我有一个SQL Server 2008数据库,其中包含一个列(datetime
数据类型)的表,可以在下订单时进行记录。
我想运行一个查询,该查询会给出在任何给定日期或日期范围内每小时订单总数的明细,但不确定编写查询的最佳方式。
答案 0 :(得分:3)
它应该是:
SELECT DATEPART(HOUR, OrderDate) AS [Hour], COUNT(*) AS [Count]
FROM [Orders]
WHERE OrderDate BETWEEN @StartDate AND @EndDate --or whatever criteria
GROUP BY DATEPART(HOUR, OrderDate)
答案 1 :(得分:0)
你可能正在寻找类似的东西:
;WITH OrdersPerHour AS
(
SELECT
CAST(OrderDate AS DATE) 'OrderDate',
DATEPART(HOUR, OrderDate) AS 'Hour',
SalesAmount
FROM
dbo.YourOrderTable
)
SELECT
OrderDate, Hour,
COUNT(*), -- number of orders
SUM(SalesAmount) -- sum of the amounts for those orders
FROM
OrdersPerHour
WHERE
OrderDate = '20120113' -- or whatever you're looking for
GROUP BY
OrderDate, Hour
当您说每小时订单总数时,不确定您是指订单金额的总和 - 或订单数量 - 如果您需要计算,只需使用{ {1}}而不是我放入查询的COUNT(*)
。
答案 2 :(得分:0)
您可以使用DATEPART
和GROUP BY
来获取此信息:
SELECT DATEPART(Hour, DateField), COUNT(*)
FROM Orders
WHERE Date = @DateParam -- or your range check here
GROUP BY DATEPART(Hour, Datefield)
答案 3 :(得分:0)
我相信它会像这样简单:
SELECT
[Hour] = DATEPART(HOUR,DateTimeField)
,Orders = COUNT(*)
FROM
tblORDERS
GROUP BY
DATEPART(HOUR,DateTimeField)