我有一个包含[更新值],[日期],[时间],[电话号码]和整数自动编号/主键列的列的表。
我想将表更新为一组,以便将日期和电话号码组合在一起(即,如果2个或更多记录具有相同的日期和电话,那么它们是“组”的一部分)但是然后同时在该组的最早时间记录中加“1”,然后为该组的下一个最早时间记录加“2”等。
只用组的计数进行更新证明很容易,但是我试图找出如何使用基于时间排序的增量值来更新每个组。
答案 0 :(得分:2)
UPDATE yt
SET [update value] = q.RowNum
FROM YourTable yt
INNER JOIN (SELECT PKColumn,
ROW_NUMBER() OVER(PARTITION BY [date], [phone number] ORDER BY [time]) AS RowNum
FROM YourTable) q
ON yt.PKColumn = q.PKColumn;
您也可以使用CTE:
执行此操作WITH cteRowNum AS (
SELECT [update value],
ROW_NUMBER() OVER(PARTIION BY [date], [phone number] ORDER BY [time]) AS RowNum
FROM YourTable
)
UPDATE cteRowNum
SET [update value] = RowNum;
答案 1 :(得分:1)
查看ROW_NUMBER()函数,例如
SELECT
Date,
PhoneNumber,
Time,
ROW_NUMBER() OVER (PARTITION BY Date, PhoneNumber ORDER BY Time ASC) AS IndexInGroup
FROM
MyTable
答案 2 :(得分:1)
此行将创建您要查找的数字。
ROW_NUMBER() OVER (PARTITION BY [phone number], [date] ORDER BY [date] ASC) Time_Sequencer