日期:2014-05-18 浏览次数:20522 次
declare @tb1 table (e int,c varchar(1))
insert into @tb1
select 1,'a' union all
select 2,'a' union all
select 2,'b' union all
select 2,'c' union all
select 3,'s' union all
select 3,'a'
declare @tb2 table (e int,c varchar(1))
insert into @tb2
select 1,'a' union all
select 1,'a' union all
select 2,'b' union all
select 2,'c' union all
select 2,'s' union all
select 3,'a'
declare @tb table(a int ,b int,c varchar(1))
--第一种情况是分成2步:
insert into @tb (c)
select e from @tb1 group by e order by count (*) desc
insert into @tb (c)
select e from @tb2 group by e order by count (*) desc
select * from @tb
/*
a b c
----------- ----------- ----
NULL NULL 2
NULL NULL 3
NULL NULL 1
NULL NULL 2
NULL NULL 1
NULL NULL 3
*/
--如果不想分为两步我来一步完成,假设再定义一个表变量
declare @tbb table(a int ,b int,c varchar(1))
insert into @tbb (c)
select e from
(
select e,1 as tn,count (*) as ecount from @tb1 group by e
union all
select e,2,count (*) from @tb2 group by e
)a
order by tn,ecount desc
--中间的1,2表示不同的表,后面的count (*)和1、2配合重新排序可以保持你要的结果
select * from @tbb