如何从SQL Server中的特定列获取唯一值?

时间:2014-11-27 05:37:31

标签: sql-server

我有一张桌子

tblFruit_ID tblFruit_FruitType tblFruit_FruitName
--------------------------------------------------
1            Citrus              Orange
2            Citrus              Lime
3            Citrus              Lemon
4            Seed                Cherry
5            Seed                Banana 

我无法仅设置distinct for tblFruit_FruitType列,如果我使用group by(我只想要计数功能),那么我也会收到错误。

我的预期输出:

tblFruit_ID   tblFruit_FruitType   tblFruit_FruitName
------------------------------------------------------
   1            citrus                   orange
   4            seed                     cherry

3 个答案:

答案 0 :(得分:0)

   SELECT  t.[tblFruit_ID],t.[tblFruit_FruitType],t.[tblFruit_FruitName]
from
(SELECT [tblFruit_ID],[tblFruit_FruitType],[tblFruit_FruitName]
FROM tbl) t
 join
(SELECT min([tblFruit_ID]) [tblFruit_ID], [tblFruit_FruitType] 
FROM tbl
GROUP BY [tblFruit_FruitType]) x
ON t.[tblFruit_ID]=x.[tblFruit_ID] 
AND
 x.[tblFruit_FruitType]=t.[tblFruit_FruitType]

答案 1 :(得分:0)

使用Window Function

;WITH cte
     AS (SELECT Row_number()OVER (PARTITION BY tblFruit_FruitType ORDER BY tblFruit_ID) rn,
                *
         FROM   tablename)
SELECT tblFruit_ID,
       tblFruit_FruitType,
       tblFruit_FruitName
FROM   cte
WHERE  rn = 1 

答案 2 :(得分:0)

我们可以使用Group By通过fruitType获取Min fruitID,然后在IN运算符中使用可用的FruitIds来获取所需的数据。

检查一下:

Select tblFruit_ID, tblFruit_FruitType, tblFruit_FruitName
From tablename
Where tblFruit_ID in 
(Select min(tblFruit_ID) From tablename Group by tblFruit_FruitType)