日期:2014-05-18  浏览次数:20488 次

请教条SQL语句!~
表1  
公司ID
公司名字
管理员ID

表2
用户ID
用户姓名
公司ID

表3
记录ID
公司ID

我要查出:         公司名称                       记录数                   管理员姓名
                                ?                                   ?                               ?
请教下


------解决方案--------------------
select
T1.公司名字 As '公司名称 '
,Sum(T3.记录ID) As '记录数 '
,T2.用户姓名 As '管理员姓名 '
from
表1 T1
Inner Join
表2 T2
On T1.公司ID=T2.公司ID
And T1.管理员ID=T2.用户ID
Inner Join
表3 T3
On T1.公司ID=T3.公司ID
------解决方案--------------------

if object_id( 'C ') is not null
drop table c
go
create table c(Id nVarchar(50),Name nvarchar(50),UID nvarchar(50))
insert c select '1 ', 'aa ', 'a1 '
union all select '2 ', 'bb ', 'b2 '
union all select '3 ', 'cc ', 'c3 '
go
if object_id( 'U ') is not null
drop table U
go
create table U(Id nvarchar(50),Name nvarchar(50),CID nvarchar(50))
insert U select 'a1 ', 'aaaaa ', '1 '
union all select 'b2 ', 'bbbbb ', '2 '
union all select 'c3 ', 'ccccc ', '3 '

if object_id( 'CU ') is not null
drop table CU
go
create table CU(ID nvarchar(50),CID nvarchar(50))
insert CU select '1001 ', '1 '
union all select '2002 ', '2 '
union all select '3003 ', '1 '


select C.Name,(select Count(ID) from CU where CID = C.ID) as 记录数,U.Name from C,U where C.UID = U.ID