我有一张桌子
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
答案 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)