正如其他人建议为LQ服务器2022所做的那样,DATE_BUCKET工程是一种治疗。
守则中的评论意见中的细节。
--===================================================================
-- Create and populate the test table as a Temp Table
-- This is NOT a part of the solution.
-- You should always post your example data as "Readily
-- Consumable" data to help others help you better and faster.
--===================================================================
--===== If it exists, drop the test table to make reruns easier.
DROP TABLE IF EXISTS #TestTable;
GO
--===== Create the test table.
CREATE TABLE #TestTable
(
OrderID INT NOT NULL PRIMARY KEY CLUSTERED
,StartTime TIME(0) NOT NULL
)
;
--===== Populate the test table with the given test data.
INSERT INTO #TestTable WITH (TABLOCK)
(OrderID, StartTime)
VALUES (1, 8:00 )
,(2, 9:30 )
,(3, 12:00 )
,(4, 13:00 )
,(5, 14:00 ) --<---<<< This was incorrect in the example output
;
--===================================================================
-- Solution for SQL Server 2022 with desired format.
-- Note that its normally not a good idea to format the output
-- in SQL Server but that s what was requested.
-- p.s. I don t use FORMAT() because it s horrible for
-- performance.
--===================================================================
SELECT OrderID
,StartTime = CONVERT(CHAR(5),StartTime,108)
,ShiftStart = CONVERT(CHAR(5),db.DBTime,108)
,EndStart = CONVERT(CHAR(5),DATEADD(hh,2,db.DBTime),108)
,Shift# = DENSE_RANK() OVER (ORDER BY db.DBTime)
FROM #TestTable --<---<<< LOOK!!! Change this to suit!!!
CROSS APPLY (VALUES (DATE_BUCKET(hh,2,StartTime)))db(DBTime)
ORDER BY OrderID
;
成果: