Select 按 nvarchar(450) 列挑战查询顺序
Select query order by nvarchar(450) column challenge
我有一个 table,其中包含列 RowId
和 Comment
,我从中 selecting 按 RowId
排序的行,到目前为止都是嗯。
但现在我需要对特定 text/string 进行注释,以便始终在不包含该 text/string 的行之后出现,而不管它们的 RowId
。我承认我是第一次接到这样的要求
示例数据
(table格式不对,1-7是RowId后面加分隔符|&然后是注释字符串值
行号 |评论
1 |在这里测试评论
2 |在这里测试更多评论
3 |测试 xxxxxxxxxx yyyyyy
4 |此行必须出现在顶部,因为它不包含单词
5 |这也必须位于包含单词
的所有行之上
6 |这个有单词测试
7 |这也有单词测试
在该示例数据中,我希望所有带有单词 test 的评论出现在所有不包含单词 test[=46] 的评论之后=]
因此,select 查询必须在包含单词 "test"
的所有其他行之前返回第 4 行和第 5 行
有什么办法可以解决这个问题吗?
在您的 ORDER BY
子句中添加 case 语句(升序)。
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
我有一个 table,其中包含列 RowId
和 Comment
,我从中 selecting 按 RowId
排序的行,到目前为止都是嗯。
但现在我需要对特定 text/string 进行注释,以便始终在不包含该 text/string 的行之后出现,而不管它们的 RowId
。我承认我是第一次接到这样的要求
示例数据 (table格式不对,1-7是RowId后面加分隔符|&然后是注释字符串值
行号 |评论
1 |在这里测试评论
2 |在这里测试更多评论
3 |测试 xxxxxxxxxx yyyyyy
4 |此行必须出现在顶部,因为它不包含单词
5 |这也必须位于包含单词
的所有行之上6 |这个有单词测试
7 |这也有单词测试
在该示例数据中,我希望所有带有单词 test 的评论出现在所有不包含单词 test[=46] 的评论之后=]
因此,select 查询必须在包含单词 "test"
的所有其他行之前返回第 4 行和第 5 行有什么办法可以解决这个问题吗?
在您的 ORDER BY
子句中添加 case 语句(升序)。
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