如何在T-SQL中使用SELECT DISTINCT和SELECT TOP n

时间:2014-09-27 18:18:12

标签: sql sql-server tsql distinct

我有这个问题:

ALTER PROCEDURE [dbo].[MySP]
    @Q Nvarchar(512)
AS BEGIN

SET @Q = REPLACE(@Q, N'%', N'');
SET @Q = N'"' + @Q + N'*' + N'"';

SELECT TOP 8 
       [KeywordId] as ID,
       [Keyword] as lable,
       [Keyword] as value
  FROM [dbo].[News_Keywords]
  WHERE CONTAINS ([Keyword], @Q)
  ORDER BY SortOrder, len([Keyword])

END

我要求的是,如何将DISTINCT功能(在[Keyword]列上)应用于此声明?这让我很困惑!提前谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用group by代替distinct。但是,您必须决定放置SortOrder的位置。这是一种方法:

SELECT TOP 8 [KeywordId] as ID, [Keyword] as label, [Keyword] as value
FROM [dbo].[News_Keywords]
WHERE CONTAINS ([Keyword], @Q)
GROUP BY KeywordId, KeyWord, SortOrder
ORDER BY SortOrder, len([Keyword]);

这是另一个:

SELECT TOP 8 [KeywordId] as ID, [Keyword] as label, [Keyword] as value
FROM [dbo].[News_Keywords]
WHERE CONTAINS ([Keyword], @Q)
GROUP BY KeywordId, KeyWord
ORDER BY MAX(SortOrder), len([Keyword]);