如何从数据集中提取时间

问题描述 投票:0回答:1

我正在使用 SSMS 处理数据集。我对 SQL 还完全陌生——还不到一个月。但我正在努力磨练以充分利用它。

我正在尝试从数据集中提取时间,以便我可以确定事件的“峰值时间”。我能够获得高峰时间,但没有时间从我的结果中显示事件的具体时间。我用过 REPLACE(REPLACE(CONVERT(VARCHAR, getdate(), 108), 'AM', ' AM'), 'PM', ' PM') AS Time

它返回我的系统时间。我如何从数据集中提取时间?

这是我的代码

SELECT REPLACE(REPLACE(CONVERT(VARCHAR, getdate(), 108), 'AM', ' AM'), 'PM', ' PM') AS Time, CASE WHEN DATEPART(HOUR, Created_time) BETWEEN 9 AND 24 THEN 'After Hour' ELSE 'Work Hour' END AS Standard_WH , COUNT(DISTINCT Ticket_ID) AS Distribution --Note: Standard_WH is used for standard work hours FROM [SLA DB].[dbo].[data_challenge] GROUP BY DATEPART(HOUR, Created_time) ORDER BY Distribution DESC

这是我的结果

Time Standard_WH Distribution -------- ----------- ------------ 20:55:40 After Hour 135 20:55:40 Work Hour 115 20:55:40 Work Hour 108 20:55:40 Work Hour 106 20:55:40 After Hour 104


sql database data-analysis
1个回答
0
投票

但是我已经创建了示例

CREATE TABLE

和示例数据:

CREATE TABLE data_challenge (
    Ticket_ID INT,
    Created_time DATETIME
);

INSERT INTO data_challenge (Ticket_ID, Created_time)
VALUES 
(1, '2023-05-01 08:30:00'),
(2, '2023-05-01 09:45:00'),
(3, '2023-05-01 15:00:00'),
(4, '2023-05-01 17:20:00'),
(5, '2023-05-01 23:00:00'),
(6, '2023-05-02 07:10:00'),
(7, '2023-05-02 14:50:00'),
(8, '2023-05-02 22:30:00');

这是一个执行某些操作的查询;但如果没有它
应该

返回什么(或为什么)的例子,我真的不能说它是否准确: SELECT CONVERT(VARCHAR, MIN(Created_time), 108) AS Earliest_Time, -- Extracts the time part from the earliest event in that hour CASE WHEN DATEPART(HOUR, Created_time) BETWEEN 9 AND 17 THEN 'Work Hour' ELSE 'After Hour' END AS Standard_WH, COUNT(DISTINCT Ticket_ID) AS Distribution FROM data_challenge GROUP BY DATEPART(HOUR, Created_time), CASE WHEN DATEPART(HOUR, Created_time) BETWEEN 9 AND 17 THEN 'Work Hour' ELSE 'After Hour' END ORDER BY Distribution DESC;

给出结果:

Earliest_Time Standard_WH Distribution ------------- ----------- ------------ 07:10:00 After Hour 1 08:30:00 After Hour 1 22:30:00 After Hour 1 23:00:00 After Hour 1 09:45:00 Work Hour 1 14:50:00 Work Hour 1 15:00:00 Work Hour 1 17:20:00 Work Hour 1 8 row(s) affected

dbFiddle

© www.soinside.com 2019 - 2024. All rights reserved.