OrderID, OrderTime, OrderItem
1, 1 am, Orange
1, 2 am, Apple
2, 3 am, Grape
3, 2 am, Apple
3, 3 am, Coconut
1, 5 am, Banana
1, 6 am, Apple
以上是原始表格。以下是我想要的表格。如果订单ID连续相同,我想将订单时间更改为最短时间。
OrderID, OrderTime, OrderItem
1, 1 am, Orange
1, 1 am, Apple
2, 3 am, Grape
3, 2 am, Apple
3, 2 am, Coconut
1, 5 am, Banana
1, 5 am, Apple
答案 0 :(得分:0)
如果您没有指定订单,那么SQL Server中的数据没有“自然”顺序,那么您无法保证返回的订单。您需要一个可用于定义order by
的列。一旦你有了这个,你可以做类似的事情
declare @data table
(
OrderItemId int identity(1,1) primary key,
OrderID int,
OrderTime datetime,
OrderItem varchar(10))
insert into @data
SELECT 1,'00:01:00','Orange' UNION ALL
SELECT 1,'00:01:00','Apple' UNION ALL
SELECT 2,'00:03:00','Grape' UNION ALL
SELECT 3,'00:02:00','Apple' UNION ALL
SELECT 3,'00:02:00','Coconut' UNION ALL
SELECT 1,'00:05:00','Banana' UNION ALL
SELECT 1,'00:05:00','Apple';
WITH cte1 AS
(
SELECT *, ROW_NUMBER() over (ORDER BY OrderItemId)-
ROW_NUMBER() over (PARTITION BY OrderID ORDER BY OrderItemId) AS Grp
FROM @data
), cte2 AS
(
SELECT *, MIN(OrderTime) OVER (PARTITION BY OrderID, Grp) AS MinOrderTime
FROM cte1
)
UPDATE cte2 SET OrderTime = MinOrderTime
SELECT OrderID,convert(varchar, OrderTime, 8) OrderItemId, OrderItem
FROM @data
ORDER BY OrderItemId