日期:2014-05-18  浏览次数:20999 次

sql server中怎么样按非递减顺序排列查询出来的数据啊
sql server中怎么样按非递减顺序排列查询出来的数据啊

------解决方案--------------------
order by 排序字段 

默认就是升序的排序
------解决方案--------------------
非递减?楼主啥意思,想要递增还是无序?
------解决方案--------------------
问得很费解啊
------解决方案--------------------
使用case when
参考:
SQL code

-->生成测试数据:
GO
IF OBJECT_ID('TBL')IS NOT NULL
DROP TABLE TBL
GO
CREATE TABLE TBL(
日期 DATE,
备注 VARCHAR(100)
)
GO
INSERT TBL
SELECT '2012-03-02','B' UNION ALL
SELECT '2012-03-05','C' UNION ALL
SELECT '2012-03-06','D' UNION ALL
SELECT '2012-03-07','E' UNION ALL
SELECT '2012-03-09','F' UNION ALL
SELECT '2012-03-11','G' UNION ALL
SELECT '2012-03-12','H' UNION ALL
SELECT '2012-03-13','I' UNION ALL
SELECT '2012-03-15','J' UNION ALL
SELECT '2012-03-19','K' UNION ALL
SELECT '2012-03-20','L'


--不使用union all
;with t
as(
select *,case when 日期>=getdate() then 1 else 0 end as A
from tbl
)

select 日期,备注 from t
order by a,(case when a=1 then 日期 end),
(case when a=0 then 日期 end) desc

/*
日期    备注
2012-03-09    F
2012-03-07    E
2012-03-06    D
2012-03-05    C
2012-03-02    B
2012-03-11    G
2012-03-12    H
2012-03-13    I
2012-03-15    J
2012-03-19    K
2012-03-20    L
*/


declrae @str varchar(100)
set @str=''
select @str=@str+','+ltrim(id) from tbla
select * from tblb
where id in(select id from tbla)
order by charindex(','+ltrim(id),@str)