(情况1)
ID Score1 Score2
1 6 NULL
2 4 NULL
3 5 NULL
如果score2为空的情况下,以Score1的分数排序
查出结果为:
ID Score1 Score2
1 6 NULL
3 5 NULL
2 4 NULL(情况2)
ID Score1 Score2
1 6 NULL
2 4 NULL
3 5 7
如果score2为不为空的情况下,以Score2为主排序
情况一应该查出结果为:
ID Score1 Score2
3 5 7
1 6 NULL
2 4 NULL
请大家帮帮我,这样的SQL语句如何写啊???????
ID Score1 Score2
1 6 NULL
2 4 NULL
3 5 NULL
如果score2为空的情况下,以Score1的分数排序
查出结果为:
ID Score1 Score2
1 6 NULL
3 5 NULL
2 4 NULL(情况2)
ID Score1 Score2
1 6 NULL
2 4 NULL
3 5 7
如果score2为不为空的情况下,以Score2为主排序
情况一应该查出结果为:
ID Score1 Score2
3 5 7
1 6 NULL
2 4 NULL
请大家帮帮我,这样的SQL语句如何写啊???????
order by isnull(Socre2,0) desc,isnull(Score1,0) desc
如果是不是int等数字类型排序会出现问题
declare @ta table(ID int, Score1 int ,Score2 int)
insert @ta
select 1 , 6 , NULL
union all select 2 , 4 , NULL
union all select 3 , 5 , 7select * from @ta
order by Score2 desc,Score1 desc(所影响的行数为 3 行)ID Score1 Score2
----------- ----------- -----------
3 5 7
1 6 NULL
2 4 NULL(所影响的行数为 3 行)
insert @ta
select 1 , 6 , NULL
union all select 2 , 4 , NULL
union all select 3 , 5 , nullselect * from @ta
order by Score2 desc,Score1 desc (所影响的行数为 3 行)ID Score1 Score2
----------- ----------- -----------
1 6 NULL
3 5 NULL
2 4 NULL(所影响的行数为 3 行)楼主在第一次排序时没有定义 desc 倒序,没定义的情况下是与第二列排序相反
select * from 表
order by cast(isnull(Socre2,0) as int ) desc,cast(isnull(Score1,0) as int) desc
这样行不
roy_88(论坛新星_燃烧你的激情!!的方法还没有实验测试完roy_88的方法后结帖
Toti的方法也是不好用的比如以下数据
ID Score1 Score2
1 6 NULL
2 3 NULL
3 2 4用Toti的方法查询是如下结果
ID Score1 Score2
3 2 4
1 6 NULL
2 3 NULL可实际我想要的是
ID Score1 Score2
1 6 NULL
3 2 4
2 3 NULL也就是说Score2有数据的话,用这条数据排序
insert T select 1, 6, NULL
union all select 2, 3, NULL
union all select 3, 2, 4select * from T
order by
(case when Score2 is null then Score1 else Score2 end)
desc--result
ID Score1 Score2
----------- ----------- -----------
1 6 NULL
3 2 4
2 3 NULL(3 row(s) affected)
create table T(ID int, Score1 int, Score2 int)
insert T select 1, 6, NULL
union all select 2, 4, NULL
union all select 3, 5, NULLselect * from T
order by
(case when Score2 is null then Score1 else Score2 end)
desc--result
ID Score1 Score2
----------- ----------- -----------
1 6 NULL
3 5 NULL
2 4 NULL(3 row(s) affected)
create table T(ID int, Score1 int, Score2 int)
insert T select 1, 6, NULL
union all select 2, 4, NULL
union all select 3, 5, 7select * from T
order by
(case when Score2 is null then Score1 else Score2 end)
desc--result
ID Score1 Score2
----------- ----------- -----------
3 5 7
1 6 NULL
2 4 NULL(3 row(s) affected)
--以上三個貼子的SELECT語句是一樣的, 表的記錄不一樣
同样推荐,应该是可以的