SQL Server 2008 R2,为另一列的每个不同值选择一列的一个值
在 SQL Server 2008 R2 上,我想为另一列的每个不同值选择一列的一个值.
On SQL server 2008 R2, I would like to select one value of a column for each distinct value of another column.
例如
name id_num
Tom 53
Tom 60
Tom 27
Jane 16
Jane 16
Bill 97
Bill 83
我需要为每个不同的名称获取一个 id_num,例如
I need to get one id_num for each distinct name, such as
name id_num
Tom 27
Jane 16
Bill 97
对于每个名称,可以随机选取 id_num(不需要是 max 或 min),只要与名称相关联即可.
For each name, the id_num can be randomly picked up (not required to be max or min) as long as it is associated with the name.
例如,对于比尔,我可以选择 97 或 83.任何一个都可以.
For example, for Bill, I can pick up 97 or 83. Either one is ok.
我知道如何编写 SQL 查询.
I do know how to write the SQL query.
谢谢
推荐答案
SELECT
name,MIN(id_num)
FROM YourTable
GROUP BY name
更新:如果你想随机选择 id_num,你可以试试这个
UPDATE: If you want pick id_num randomly, you may try this
WITH cte AS (
SELECT
name, id_num,rn = ROW_NUMBER() OVER (PARTITION BY name ORDER BY newid())
FROM YourTable
)
SELECT *
FROM cte
WHERE rn = 1
SQL 小提琴演示
相关文章