sql查询来计算每小时的数据输入

时间:2016-06-13 09:29:40

标签: c# sql sql-server visual-studio

我想显示特定行的每小时(1小时时间间隔)内当前数据输入的计数,最后显示所有小时的累计数。 表详情:

CREATE TABLE [dbo].[ProductTable] (
    [Id]         INT          IDENTITY (1, 1) NOT NULL,
    [ProductID]  INT          NOT NULL,
    [EmployeeID] INT          NOT NULL,
    [Operation]  VARCHAR (50) NOT NULL,
    [Section]    NCHAR (10)   NOT NULL,
    [Line]       INT          NOT NULL,
    [Date]       DATETIME     DEFAULT (getdate()) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC),
);

我正在使用Microsoft Visual Studio SQL服务器 我写了这么多,但不知道每小时都要概括一下

SELECT COUNT(Id) AS Expr1
FROM ProductTable
WHERE (Line = 2)
AND (CONVERT(VARCHAR(10), Date, 105) = CONVERT(VARCHAR(10), GETDATE(), 105))
AND (DATEPART(hour, GETDATE()) BETWEEN 9 AND 10)`

ProductTable数据 ProductTable Data

使用"案例"时出错 Error on using case

2 个答案:

答案 0 :(得分:1)

听起来你想按小时分组

SELECT      DATEPART(hour, date) as TimeOfDay,  COUNT(Id) AS Entries
FROM            ProductTable
WHERE        (Line = 2) AND cast ([date] as date) =cast (getdate() as date) 
GROUP BY DATEPART(hour, date) 

要获取当天所有小时的累积数,请使用分组集

      SELECT       ISNULL(cast(DATEPART(hour,[date]) as varchar(5)),'Total') as TimeOfDay, COUNT(Id) AS Entries
        FROM            ProductTable
        WHERE        (Line = 2) AND cast ([date] as date) =cast (getdate() as date)  
        GROUP BY GROUPING SETS (DATEPART(hour, [date]) , ())
ORDER BY   ISNULL(cast(DATEPART(hour, [date]) as varchar(5)),'Total')

答案 1 :(得分:0)

只需使用group by子句

SELECT        COUNT(Id) AS Expr1
FROM            ProductTable 
where (Line = 2) AND (CONVERT(Date,[Date])) = CONVERT(DATE,GETDATE()) 
GROUP BY DATEPART(HOUR, Date)