日期:2014-05-19  浏览次数:20562 次

救命!!Sql语句问题
现有两个表A和B,A.id   与B.aid关联,一个A对应多个B,B里面有一个关键字是记录顺序的B.order,这个时候我需要联合查询A和B,得到每个A有多少个B,关键是必须按照B.order得到这个值,我的语句如下

select   count(A.id)   as   newid   where   A.id=B.aid   group   by   A.id   order   by   B.order

但是提示说B.order不再聚合函数里,也不在groupby子句中,很郁闷,在线等待高手指点。。。。

------解决方案--------------------
select b.id ,count(*) as newid from A ,B where A.id=B.aid group by b.id order by B.order
------解决方案--------------------
select A.ID,B.order,count(A.id) as newid where A.id=B.aid group by A.id,B.order order by B.order
------解决方案--------------------
select A.id,count(1) as as newid
from A
join B on A.id = B.aid
group by A.id

或者
select A.id,count(A.id) as newid
from A,B where A.id=B.aid group by A.id

另外,关键是必须按照B.order得到这个值 什么意思?
------解决方案--------------------
select A.id ,count(*) as [newid]
from A inner join B on A.id=B.aid
group by A.id
order by min(B.[order])

------解决方案--------------------

create table a
(
id int
)

create table b
(
id varchar(1),
aid int,
[order] int
)


insert into a select 1
insert into a select 2

insert into b select 'a ',1,1
insert into b select 'b ',1,2
insert into b select 'c ',2,3
insert into b select 'd ',2,4


select a.id ,count(*) as [newid]
from a inner join b on a.id=b.aid
group by a.id
order by min(b.[order])

--结果
1 2
2 2