You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将SQL表中指定内容的行置顶后按id排序?

SQL Server指定行置顶后按ID排序

需求:将表中comment列值为my comment的行排在结果集最顶部,剩余行再按id列升序排列。

实现SQL语句:

SELECT *
FROM 你的表名
ORDER BY 
    CASE WHEN comment = 'my comment' THEN 0 ELSE 1 END,
    id ASC;

效果示例

排序前数据:

other comment
other comment
other comment
my comment
other comment
my comment
my comment

排序后结果:

my comment
my comment
my comment
other comment
other comment
other comment
other comment

原理:通过CASE语句给目标行分配更低的排序优先级(0),其他行优先级为1,确保目标行排在最前;之后按id升序完成剩余行的排序。

内容的提问来源于stack exchange,提问作者ryandra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 20:32:41