简体   繁体   English

T-SQL 强制 Select 结果具有主键

[英]T-SQL Force Select results to have a Primary Key

I have a large set of imperfect data, from this data I reverse engineering a table for the coding used.我有一大组不完善的数据,从这些数据中我对所用编码的表进行逆向工程。

For this particular task, it is know that all records with a specific division code should all have the same group ID and plan ID (which are not included in the data) from another source I been able to add a close but imperfect (and incomplete) mapping of the group ID and plan ID.对于这个特定的任务,知道具有特定部门代码的所有记录都应该具有来自另一个来源的相同的组 ID 和计划 ID(不包含在数据中)我能够添加一个接近但不完美(并且不完整) ) 组 ID 和计划 ID 的映射。 Now I want to work backwards and build a division mapping table.现在我想向后工作并建立一个划分映射表。 I have gotten data down to a format like this:我已经把数据变成了这样的格式:

Division Year   Group   Plan    Cnt
52       2019   30      101    9031
52       2020   30      101    9562
54       2019   60      602    3510
54       2020   60      602    3385
56       2019   76      904    1113
56       2020   76      905    1125
56       2020   76      001    6

The Division and Year columns should from a primary key. Division 和 Year 列应该来自一个主键。 As you can see 56, 2020 is not unique, but by looking at the cnt column it is easy to see that the record with a count of 6 is a bad record and should be dropped.如您所见,2020 年不是唯一的 56,但是通过查看 cnt 列很容易看出计数为 6 的记录是不良记录,应该删除。

What I need is a method to return each division and year pair once with the group and plan IDs that have the largest count.我需要的是一种方法,可以将每个部门和年份对与具有最大计数的组和计划 ID 一起返回一次。

Thank You谢谢你

I found the answer using the Rank() function and WHERE clause:我使用 Rank() function 和 WHERE 子句找到了答案:

SELECT *
FROM (
SELECT Division, Year, Group, Plan_Cd
     , RANK() OVER (PARTITION BY Division, Year ORDER BY Cnt DESC ) AS 'rk'
FROM DivisionMap ) R
WHERE rk = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM