SQL服务器window功能实现问题
SQL Server window function implementation issue
我有一个 table 结构,如下所示:
我有以下查询来从 table 中获取唯一结果:
WITH Dupes AS
(
SELECT
ID, Template_ID, Address, Job_Number, Other_Info,
Assigned_By, Assignees, Active, seen,
ROW_NUMBER() OVER (PARTITION BY Template_ID,Job_Number ORDER BY ID) AS RowNum
FROM
Schedule
WHERE
Assignees IN ('9', '16', '22')
)
SELECT
ID, Template_ID, Job_Number, Address, Other_Info,
Assigned_By, Assignees, Active, seen
FROM
Dupes
WHERE
RowNum = 1
上述查询的输出是:
如果Job_Number和Template_ID相同,只有return一行(第一行使用ID)。这就是我使用 ROW_NUMBER() OVER(PARTITION BY Template_ID,Job_Number ORDER BY ID) AS RowNum
的原因。我不知道如何解决这个问题,因为我很少使用这个功能。
我需要得到如下输出:
更新代码
尝试了以下代码:
您似乎在尝试按 Job_Number
分组,删除 partition by
子句中的 Template_ID
WITH Dupes AS
(
SELECT ID,Template_ID,Address,Job_Number,Other_Info,Assigned_By,Assignees,Active,seen,
ROW_NUMBER() OVER(PARTITION BY rtrim(ltrim(Job_Number)) ORDER BY ID) AS RowNum
FROM Schedule
WHERE Assignees IN('9','16','22')
)
SELECT ID,Template_ID,Job_Number,Address,Other_Info,Assigned_By,Assignees, Active,seen FROM Dupes WHERE RowNum=1
我有一个 table 结构,如下所示:
我有以下查询来从 table 中获取唯一结果:
WITH Dupes AS
(
SELECT
ID, Template_ID, Address, Job_Number, Other_Info,
Assigned_By, Assignees, Active, seen,
ROW_NUMBER() OVER (PARTITION BY Template_ID,Job_Number ORDER BY ID) AS RowNum
FROM
Schedule
WHERE
Assignees IN ('9', '16', '22')
)
SELECT
ID, Template_ID, Job_Number, Address, Other_Info,
Assigned_By, Assignees, Active, seen
FROM
Dupes
WHERE
RowNum = 1
上述查询的输出是:
如果Job_Number和Template_ID相同,只有return一行(第一行使用ID)。这就是我使用 ROW_NUMBER() OVER(PARTITION BY Template_ID,Job_Number ORDER BY ID) AS RowNum
的原因。我不知道如何解决这个问题,因为我很少使用这个功能。
我需要得到如下输出:
更新代码
尝试了以下代码:
您似乎在尝试按 Job_Number
分组,删除 partition by
子句中的 Template_ID
WITH Dupes AS
(
SELECT ID,Template_ID,Address,Job_Number,Other_Info,Assigned_By,Assignees,Active,seen,
ROW_NUMBER() OVER(PARTITION BY rtrim(ltrim(Job_Number)) ORDER BY ID) AS RowNum
FROM Schedule
WHERE Assignees IN('9','16','22')
)
SELECT ID,Template_ID,Job_Number,Address,Other_Info,Assigned_By,Assignees, Active,seen FROM Dupes WHERE RowNum=1