通过nvarchar(450)列挑战选择查询顺序

时间:2016-12-02 08:50:52

标签: sql-server tsql sql-order-by

我有一个包含RowIdComment列的表格,我正在选择按RowId排序的行,到目前为止一切顺利。

但现在我要求对特定文本/字符串的注释始终位于不包含该文本/字符串的行之后,而不管其RowId。我必须承认这是我第一次收到这样的要求。

示例数据 (表格格式不正确,1-7是RowId后跟分隔符|&然后是注释字符串值

RowId |评论

1 |在这里测试评论
   2 |在这里测试评论

3 |测试xxxxxxxxxx yyyyyy

4 |此行必须显示在顶部,因为它不包含单词

5 |这也必须高于包含单词

的所有行

6 |这个有单词test

7 |这个单词也是测试

在该示例数据中,我希望所有带有测试一词的评论都出现在所有不包含测试

一词的评论之后

所以第4行和第4行在包含单词“test”

的所有其他行之前,select查询必须返回5

我有什么想法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:3)

将case语句添加到ORDER BY子句(升序)。

CASE
    WHEN Comment LIKE '%test%' THEN 1
    ELSE 0
END AS OrderByColumn

不包含字符串的所有内容都将首先出现,其他所有内容都将排在第二位。您希望这是ORDER BY

中的第一项

这是一个非常基本的版本;

测试数据

CREATE TABLE #TestData (RowID int, Comment nvarchar(100))
INSERT INTO #TestData (RowID, Comment)
VALUES
 (1,'test comment here')
,(2,'test comment more here')
,(3,'test xxxxxxxxxx yyyyyy')
,(4,'this row must appear at the top because it does not contain the word')
,(5,'this must also be above all rows that contain the word')
,(6,'this one has the word test')
,(7,'this has the word test also')

查询

SELECT
     RowID
    ,Comment
FROM #TestData
ORDER BY
    CASE WHEN Comment LIKE '%test%' THEN 1 ELSE 0 END ASC
   ,RowID ASC

结果

RowID   Comment
4       this row must appear at the top because it does not contain the word
5       this must also be above all rows that contain the word
1       test comment here
2       test comment more here
3       test xxxxxxxxxx yyyyyy
6       this one has the word test
7       this has the word test also
相关问题