SQL server 2008 R2, select one value of a column for each distinct value of another column(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 小提琴演示
这篇关于SQL Server 2008 R2,为另一列的每个不同值选择一列的一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL Server 2008 R2,为另一列的每个不同值选择一列
基础教程推荐
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 在多列上分布任意行 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
