我想在连续出现时只给组合行号,比如 请指导如何在Tsql中获得这种类型的序列编号
我试过
ROW_NUMBER() Over (Partition by name,Order_type Order by REC_TS)
where record REC_TS is the time of order.
Name: Order type: Seq Number:
AAA ONLINE 1
AAA ONLINE 2
AAA STORE 1
AAA SPOT 1
AAA STORE 1
AAA SPOT 1
AAA SPOT 2
AAA ONLINE 1
答案 0 :(得分:1)
将ROW_NUMBER()
与CTE一起使用。该查询基于当存在连续值时,ROW_NUMBER () OVER (ORDER BY REC_TS)
和ROW_NUMBER () OVER (PARTITION BY Name, OrderType ORDER BY REC_TS)
之间的差异将保持不变。
像这样的东西
DECLARE @Table1 TABLE
(
Name VARCHAR(10),
OrderType VARCHAR(10),
REC_TS DATETIME
)
Insert into @Table1
SELECT 'AAA','ONLINE','2014-09-01'
UNION ALL SELECT 'AAA','ONLINE','2014-09-02'
UNION ALL SELECT 'AAA','STORE','2014-09-03'
UNION ALL SELECT 'AAA','SPOT','2014-09-04'
UNION ALL SELECT 'AAA','STORE','2014-09-05'
UNION ALL SELECT 'AAA','SPOT','2014-09-06'
UNION ALL SELECT 'AAA','SPOT','2014-09-07'
UNION ALL SELECT 'AAA','ONLINE','2014-09-07'
;WITH CTE
AS (SELECT *,
ROW_NUMBER () OVER (ORDER BY REC_TS) - ROW_NUMBER () OVER (PARTITION BY Name,
OrderType
ORDER BY REC_TS) AS RowGroup
FROM @Table1)
SELECT ROW_NUMBER () OVER (PARTITION BY RowGroup,
Name,
OrderType
ORDER BY REC_TS) AS Sequence,
Name,OrderType
FROM CTE
ORDER BY REC_TS;
答案 1 :(得分:0)
试试这个:
CREATE TABLE Orders
(
Name VARCHAR(10),
OrderType VARCHAR(10),
REC_TS DATETIME
)
Insert into Orders
VALUES
('AAA','ONLINE','2014-09-01'),
('AAA','ONLINE','2014-09-02'),
('AAA','STORE','2014-09-03'),
('AAA','SPOT','2014-09-04'),
('AAA','STORE','2014-09-05'),
('AAA','SPOT','2014-09-06'),
('AAA','SPOT','2014-09-07'),
('AAA','ONLINE','2014-09-07')
;WITH OrdersRN
AS
(
SELECT [Name], OrderType, ROW_NUMBER() OVER (ORDER BY [REC_TS]) AS RN, [REC_TS]
FROM Orders
),
OrdersRecurs
AS
(
SELECT O1.Name, O1.OrderType, 1 As Seq, O1.RN
FROM OrdersRN O1
WHERE RN = 1
UNION ALL
SELECT O1.Name, O1.OrderType,
CASE
WHEN Prev.Name IS NULL THEN 1
WHEN Prev.Name = O1.Name AND Prev.OrderType = O1.OrderType THEN Prev.Seq + 1
ELSE 1
END As Seq,
O1.RN
FROM OrdersRN O1
INNER JOIN OrdersRecurs Prev
ON Prev.RN = O1.RN - 1
WHERE O1.RN <> 1
)
SELECT O.[Name], O.OrderType, O.[Seq]
FROM OrdersRecurs O