select b,c,min(a) a from tb group by b,c order by a desc
根据b,c过滤重复,那么相同的bc 可能对应不同的a ,你打算怎么排序呢?
declare @t table (b int,c int,a int) insert into @t select 1,1,4 union all select 1,1,2 union all select 2,2,3 union all select 3,3,6 union all select 2,2,5 union all select 3,3,1SELECT distinct b,c from @t /* b c ----------- ----------- 1 1 2 2 3 3 */告诉我你想要什么样的结果?
declare @t table (b int,c int,a int) insert into @t select 1,1,4 union all select 1,1,2 union all select 2,2,3 union all select 3,3,6 union all select 2,2,5 union all select 3,3,1 --按相同b,c对应的最小a排序 SELECT b,c from @t GROUP BY b,c ORDER BY MIN(a) /* b c ----------- ----------- 3 3 1 1 2 2 */ --按相同b,c对应的最大a排序 SELECT b,c from @t GROUP BY b,c ORDER BY max(a) /* b c ----------- ----------- 1 1 2 2 3 3 */ --按相同b,c对应的平均a排序 SELECT b,c from @t GROUP BY b,c ORDER BY avg(a) /* b c ----------- ----------- 1 1 3 3 2 2 */
楼主你这个排序逻辑是不符合sql语法的。 根据sql的执行顺序,order by 是最后执行。 在order by 之前就根据select 筛选出了最后的列。 如果select 中没有a列,则order by 中是访问不到的。
select b,c,min(a) a
from tb
group by b,c
order by a desc
declare @t table (b int,c int,a int)
insert into @t
select 1,1,4 union all
select 1,1,2 union all
select 2,2,3 union all
select 3,3,6 union all
select 2,2,5 union all
select 3,3,1SELECT distinct b,c from @t
/*
b c
----------- -----------
1 1
2 2
3 3
*/告诉我你想要什么样的结果?
declare @t table (b int,c int,a int)
insert into @t
select 1,1,4 union all
select 1,1,2 union all
select 2,2,3 union all
select 3,3,6 union all
select 2,2,5 union all
select 3,3,1
--按相同b,c对应的最小a排序
SELECT b,c from @t GROUP BY b,c ORDER BY MIN(a)
/*
b c
----------- -----------
3 3
1 1
2 2
*/
--按相同b,c对应的最大a排序
SELECT b,c from @t GROUP BY b,c ORDER BY max(a)
/*
b c
----------- -----------
1 1
2 2
3 3
*/
--按相同b,c对应的平均a排序
SELECT b,c from @t GROUP BY b,c ORDER BY avg(a)
/*
b c
----------- -----------
1 1
3 3
2 2
*/
根据sql的执行顺序,order by 是最后执行。
在order by 之前就根据select 筛选出了最后的列。
如果select 中没有a列,则order by 中是访问不到的。