SQL 自定义排序

--用case排序 CASE c_id  WHEN '15' THEN 1 else 2 end
select top 4 c.* from m3_channel c where  isnull(c.c_upload_mediaserver,'-1') <> '0'
ORDER BY CASE c_id  WHEN '15' THEN 1 WHEN '14' THEN 2 WHEN '17' THEN 3 WHEN '16' THEN 4 ELSE 5  END

--用charindex排序 所有的都指定
select  * from m3_channel  where  isnull(c_upload_mediaserver,'-1') <> '0'
order by charindex(','+cast(c_id as varchar(20))+',',',14,16,13,15,18,17,')
--用charindex排序 c_id in 的ID都指定
select top 4 * from m3_channel  where  isnull(c_upload_mediaserver,'-1') <> '0' and c_id in (16,15,14,13)
order by charindex(','+cast(c_id as varchar(20))+',',',14,16,13,15,')

--SQL变量
DECLARE @SortKey VARCHAR(300)
SET @SortKey='直播频道4,直播频道3,直播频道6,直播频道5'
select top 4 c.* from m3_channel c where  isnull(c.c_upload_mediaserver,'-1') <> '0'
ORDER BY CHARINDEX(c_name,@SortKey)

你可能感兴趣的:(sql)