Sql server 按nvarchar(450)列挑战选择查询顺序

Sql server 按nvarchar(450)列挑战选择查询顺序,sql-server,tsql,sql-order-by,Sql Server,Tsql,Sql Order By,我有一个包含列RowId和Comment的表,从中我选择了按RowId排序的行,到目前为止一切正常 但现在,我有一个要求,即在不包含该文本/字符串的行之后总是有带有特定文本/字符串的注释,而不管它们的RowId。我必须承认这是我第一次接到这样的要求 样本数据 (表格格式不正确,1-7是RowId,后跟分隔符|&然后是注释字符串值。) RowId|评论 1 |此处的测试注释 2 |此处有更多测试评论 3 |测试XXXXXXXXX YYYYY 4 |此行必须出现在顶部,因为它不包含单词 5 |这也必

我有一个包含列
RowId
Comment
的表,从中我选择了按
RowId
排序的行,到目前为止一切正常

但现在,我有一个要求,即在不包含该文本/字符串的行之后总是有带有特定文本/字符串的注释,而不管它们的
RowId
。我必须承认这是我第一次接到这样的要求

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

RowId|评论

1 |此处的测试注释
2 |此处有更多测试评论

3 |测试XXXXXXXXX YYYYY

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

5 |这也必须位于包含单词的所有行之上

6 |这个有单词测试

7 |这也有单词测试

在该示例数据中,我希望所有带有单词test的注释位于所有不包含单词test的注释之后

因此,select查询必须在包含单词“test”的所有其他行之前返回第4行和第5行


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

在您的
ORDER BY
子句(升序)中添加一个case语句

所有不包含该字符串的内容都将排在第一位,其他内容将排在第二位。您希望这是您的
订单中的第一项

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

测试数据

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')
质疑

结果

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

我喜欢这个解决方案,但我太笨了,无法理解为什么RowID为6和7的行不会出现在输出的末尾。这两个注释都包含“test”一词.既然6>3,我希望RowID为3的那一行后面的那一行。我遗漏了什么?那是因为我很愚蠢,没有将RowID包含在示例输出中的ORDER BY中。我现在更新了答案:)
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