A表字段有 : B表字段有有 id title content id belongid title content
1 1 1 1 1 1 1
2 1 1 2 1 1 1
3 1 1 3 2 1 1上面的意思就是 A表中ID为1的有2个子类,id为2的有1个,其中b表是A表的子类,就是说belongid就是a表的id,我想在A来排序,,是根据A表的子类多排前面
1 1 1 1 1 1 1
2 1 1 2 1 1 1
3 1 1 3 2 1 1上面的意思就是 A表中ID为1的有2个子类,id为2的有1个,其中b表是A表的子类,就是说belongid就是a表的id,我想在A来排序,,是根据A表的子类多排前面
解决方案 »
- SQL Manager 2005 for SQL Sever 新手入门
- 在sql server2000中如果从一个数据库中误删了一个表,应如何恢复它
- sql子查询,去重复!!!
- 新人求助问题。关于SQL2000的安装~
- 根据出生日期计算年龄作为新字段
- 紧急求救:sql server中,误删除一数据库,如何回复???很急!请大虾救命,在线等待!
- 怎么查找数据库中的某个字段
- 关于like,高手指教!!!
- 请问在SQLSERVER里什么地方改端口号?》?
- 20万条记录,进行模糊查询速度非常慢,如何提高查询速度
- 一个超复杂 的SQL 大家帮看一下啊
- 一个比较复杂的sql问题,单行变成多行的报表tsql块!
from a
order by (select count(*) from b where b.belongid=a.id)
改了一下, 改成2的子类更多, 2排在前面-- =============================================
-- Author: T.O.P
-- Create date: 20091202
-- Version: SQL SERVER 2000
-- =============================================
declare @tb1 table([id] int,[title] int,[content] int)
insert @tb1
select 1,1,1 union all
select 2,1,1 union all
select 3,1,1declare @tb2 table([id] int,[belongid] int,[title] int,[content] int)
insert @tb2
select 1,1,1,1 union all
select 2,2,1,1 union all
select 3,2,1,1select id, title, content
from (
select a.id, a.title, a.content, count(b.belongid) as icount
from @tb1 a left join @tb2 b on a.id= b.belongid
group by a.id, a.title, a.content
) t
order by t.icount desc--测试结果:
/*
id title content
----------- ----------- -----------
2 1 1
1 1 1
3 1 1(所影响的行数为 3 行)警告: 聚合或其它 SET 操作消除了空值。
*/
from @tb1 a
order by (select count(*) from @tb2 t where t.belongid=a.id)
desc/*
id title content
----------- ----------- ----------- -----------
2 1 1 2
1 1 1 1
3 1 1 0(所影响的行数为 3 行)*/
insert @tb1
select 1,1,1 union all
select 2,1,1 union all
select 3,1,1declare @tb2 table([id] int,[belongid] int,[title] int,[content] int)
insert @tb2
select 1,1,1,1 union all
select 2,2,1,1 union all
select 3,2,1,1select m.* from @tb1 m left join (select belongid , count(1) cnt from @tb2 group by belongid) n
on m.id = n.belongid order by n.cnt desc/*
id title content
----------- ----------- -----------
2 1 1
1 1 1
3 1 1(所影响的行数为 3 行)
*/
declare @ta table (id int,title int,content int)
insert into @ta
select 1,1,1 union all
select 2,1,1 union all
select 3,1,1
--> 测试数据: @tb
declare @tb table (id int,belongid int,title int,content int)
insert into @tb
select 1,1,1,1 union all
select 2,1,1,1 union all
select 3,2,1,1 select t1.* from @ta t1,(
select a.id,px=sum(case when b.belongid is null then 0 else 1 end ) from @ta a left join @tb b
on a.id=b.belongid
group by a.id
)t2
where t1.id=t2.id
order by px desc(3 行受影响)
id title content
----------- ----------- -----------
1 1 1
2 1 1
3 1 1(3 行受影响)