我有三栏 PID,AppNo和ProcessedDate 我需要查询以以下格式更新AppNo
PID AppNo ProcessedDate
11 1 09/30/2019 18:21
3 1 09/25/2019 08:37
3 2 09/25/2019 08:37
11 1 09/25/2019 08:39
11 2 09/25/2019 08:40
7 1 09/26/2019 14:19
7 2 09/26/2019 14:20
7 3 09/26/2019 14:22
2 1 09/26/2019 14:23
11 1 09/26/2019 14:23
11 2 09/26/2019 14:24
11 3 09/26/2019 14:24
3 1 09/26/2019 14:24
目前,“ AppNo”列为空。
这是行不通的SQL
SELECT AppNo, ProcessedDate,pid
,Row_Number() OVER(PARTITION BY pid, ProcessedDate ORDER BY ProcessedDate) AS rn
select * FROM table
答案 0 :(得分:0)
查询。
SELECT pid as ProjectID
, Row_Number() OVER(PARTITION BY pid, ProcessedDate ORDER BY ProcessedDate) AS AppNo
, ProcessedDate
FROM table
答案 1 :(得分:0)
如果row_number不应将时间视为以下时间,则将ProcessedDate
转换为日期:
SELECT AppNo, ProcessedDate,pid
,Row_Number() OVER(PARTITION BY pid, convert (date,ProcessedDate)
ORDER BY ProcessedDate) AS rn
from @T
您可以将更新写为:
with CTE as(
SELECT ProcessedDate,pid
,Row_Number() OVER(PARTITION BY pid, convert (date,ProcessedDate)
ORDER BY ProcessedDate) AS rn
from Test
)
update CTE
set AppNo = rn
并将结果测试为:
Select AppNo ,
Row_Number() OVER(PARTITION BY pid, convert (date,ProcessedDate)
ORDER BY ProcessedDate) AS rn,
ProcessedDate,
pid
from Test
答案 2 :(得分:0)
您似乎正在寻找更新原始表格的方法。您可以在CTE中使用ROW_NUMBER()
对具有相同日期(无时间)和pid的组(按日期(有时间)排序)对记录进行排名,然后即时进行更新:
WITH cte AS (
SELECT
pid,
ProcessedDate,
AppNo,
ROW_NUMBER() OVER(PARTITION BY pid, CAST(ProcessedDate AS DATE) ORDER BY ProcessedDate) rn
FROM mytable
)
UPDATE cte SET AppNo = rn
原始数据:
PID | AppNo | ProcessedDate --: | ----: | :--------------- 11 | null | 09/30/2019 18:21 3 | null | 09/25/2019 08:37 3 | null | 09/25/2019 08:37 11 | null | 09/25/2019 08:39 11 | null | 09/25/2019 08:40 7 | null | 09/26/2019 14:19 7 | null | 09/26/2019 14:20 7 | null | 09/26/2019 14:22 2 | null | 09/26/2019 14:23 11 | null | 09/26/2019 14:23 11 | null | 09/26/2019 14:24 11 | null | 09/26/2019 14:24 3 | null | 09/26/2019 14:24
运行查询后:
PID | AppNo | ProcessedDate --: | ----: | :--------------- 11 | 1 | 09/30/2019 18:21 3 | 1 | 09/25/2019 08:37 3 | 2 | 09/25/2019 08:37 11 | 1 | 09/25/2019 08:39 11 | 2 | 09/25/2019 08:40 7 | 1 | 09/26/2019 14:19 7 | 2 | 09/26/2019 14:20 7 | 3 | 09/26/2019 14:22 2 | 1 | 09/26/2019 14:23 11 | 1 | 09/26/2019 14:23 11 | 2 | 09/26/2019 14:24 11 | 3 | 09/26/2019 14:24 3 | 1 | 09/26/2019 14:24
答案 3 :(得分:0)
您必须仅使用带有日期部分的分区,例如:
SELECT AppNo, ProcessedDate,pid
,Row_Number() OVER(PARTITION BY pid, CONVERT(VARCHAR(10), ProcessedDate, 111) ORDER BY ProcessedDate) AS rn
select * FROM table
答案 4 :(得分:0)
如果ProcessedDate
的类型为DATETIME
,则可以
SELECT
pid,
ROW_NUMBER() OVER (
PARTITION BY pid, convert(date, ProcessedDate)
ORDER BY pid, ProcessedDate
) AppNo,
ProcessedDate
FROM table
如果ProcessedDate
的类型为VARCHAR
,则可以
;WITH
t as (
SELECT pid, convert(datetime, ProcessedDate, 120) ProcessedDate
from table
)
SELECT
pid,
ROW_NUMBER() OVER (
PARTITION BY pid, convert(date, ProcessedDate)
ORDER BY pid, ProcessedDate
) AppNo,
ProcessedDate
FROM t