Pertanyaan query sql untuk menghitung entri data setiap jam


Saya ingin menampilkan hitungan entri data hari ini selama setiap jam (interval waktu 1 jam) untuk baris tertentu dan akhirnya kumulatif dari semua jam. Detail tabel:

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),
);

Saya menggunakan server Microsoft Visual Studio SQL Saya telah menulis begitu banyak tetapi tidak tahu untuk menyamaratakan setiap jam

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)`

Data ProductTable ProductTable Data

Kesalahan saat menggunakan "kasus" Error on using case


4
2018-06-13 09:29


asal


Jawaban:


Kedengarannya seperti Anda ingin mengelompokkan berdasarkan jam dari hari

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) 

Untuk mendapatkan kumulatif dari semua jam dalam sehari, gunakan kumpulan pengelompokan

      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
2018-06-13 09:34



cukup gunakan grup dengan klausa

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

0
2018-06-13 09:39