SQL仅在一个特定字段上使用distinct

时间:2013-06-03 07:15:09

标签: sql sql-server database

如何在shortDesc字段中仅选择一行?我不关心哪一行,但只需要一行。

我的表格摘录是

|longDescr|shortDesc|
|---------|---------|
| First 1 | first   |
| First 2 | first   |
| First 3 | first   |
| First 4 | first   |
| Second 1| second  |
| Second 2| second  |
| Second 3| second  |
| Second 4| second  |
| Third 1 | third   |
| Third 2 | third   |
| Third 3 | third   |

我期望的是光标结果:

|longDescr|shortDesc|
|---------|---------|
| First 1 | first   |
| Second 1| second  |
| Third 1 | third   |

我真的不知道如何编写SQL查询。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

Select longDescr,shortDesc from
(Select Row_Number() Over(Partition By shortDesc order by shortDesc) as Rows ,*
 from TableName ) t 
where Rows=1;

答案 1 :(得分:1)

使用GROUP BY子句尝试这个:

SELECT MIN(longDescr) AS longDescr, shortDesc
FROM MyTable
GROUP BY shortDesc

输出:

╔═══════════╦═══════════╗
║ LONGDESCR ║ SHORTDESC ║
╠═══════════╬═══════════╣
║ First 1   ║ first     ║
║ Second 1  ║ second    ║
║ Third 1   ║ third     ║
╚═══════════╩═══════════╝

请参阅this SQLFiddle

您可以根据自己的要求使用MIN()MAX()功能。