2017-07-05 68 views
0

我有一個表搜索按順序選取組,欄目有:SQL由不同

id(int), title(nvarchar), count(int), expression(nvarchar) 

與價值觀:

1, aaa, 5, car 
2, aaa, 5, car poster 
3, bbb, 8, car magazine 
4, bbb, 8, car tv 
5, ccc, 12, boat 
6, ccc, 12 , boat tv 

我需要以下結果

4, bbb, 8, car tv 
3, bbb, 8, car magazine 
2, aaa, 5, car poster 
1, aaa, 5, car 

或更好的結果無論從4,32,1 這樣的:

3, bbb, 8, car magazine 
2, aaa, 5, car poster 

我嘗試這樣做:

SELECT title 
FROM 
    (SELECT * 
    FROM Search 
    ORDER BY count DESC) 
WHERE expression 
LIKE '%car%' 
GROUP BY title 

我也嘗試了DISTINCT

+1

在您的「更好的結果」中,爲什麼汽車電視會消失?因爲它對於給定的標題具有較高的ID,並且您想要顯示較低的ID? – xQbert

+0

nope ...我只想要一個標題bbb和一個aaa ...不要緊,哪個 –

回答

0

使用CTEROW_NUMBER功能與身份證一起遞減計數找到匹配的行,並責令其打破領帶。然後選擇每個分區(標題)中第一個編號的行。

WITH cteFindCar AS (
    SELECT id, title, count, expression, 
      ROW_NUMBER() OVER(PARTITION BY title ORDER BY count DESC, id) AS RowNum 
     FROM search 
     WHERE expression LIKE '%car%' 
) 
SELECT id, title, count, expression 
    FROM cteFindCar 
    WHERE RowNum = 1; 
+0

非常感謝...它的工作原理 –