急急急!!!求高手指点,Sql server 根据某个字段查询两个表的总记录数?
比如:表AIdUserId(外键对应C中的Id)CompanyName12f22d32f41h56j63g73m表BIdUserId(外键对应C中的Id)Persnoal...
比如:
表A
Id UserId(外键对应C中的Id) CompanyName
1 2 f
2 2 d
3 2 f
4 1 h
5 6 j
6 3 g
7 3 m
表 B
Id UserId(外键对应C中的Id) PersnoalName
1 3 c
2 6 f
3 4 g表CId UserName1 liu2 jjj3 dddd4 eee5 rrr6 sss
查询结果:
UserName 表A的数目 表B的数目 总数目
jjj 3 0 3
liu 1 0 1
dddd 2 1 3
sss 1 1 2
eee 0 1 1
求高手指点。 展开
表A
Id UserId(外键对应C中的Id) CompanyName
1 2 f
2 2 d
3 2 f
4 1 h
5 6 j
6 3 g
7 3 m
表 B
Id UserId(外键对应C中的Id) PersnoalName
1 3 c
2 6 f
3 4 g表CId UserName1 liu2 jjj3 dddd4 eee5 rrr6 sss
查询结果:
UserName 表A的数目 表B的数目 总数目
jjj 3 0 3
liu 1 0 1
dddd 2 1 3
sss 1 1 2
eee 0 1 1
求高手指点。 展开
展开全部
你先试试这个:
WITH AA AS
(SELECT USERID, COUNT(USERID) ACOUNT FROM A GROUP BY USERID),
BB AS
(SELECT USERID, COUNT(USERID) BCOUNT FROM B GROUP BY USERID)
SELECT C.USERNAME,
NVL(AA.ACOUNT, 0) 表A数目,
NVL(BB.BCOUNT, 0) 表B数目,
NVL(AA.ACOUNT, 0) + NVL(BB.BCOUNT, 0) 总数目
FROM AA, BB, C
WHERE AA.USERID(+) = C.USERID
AND BB.USERID(+) = C.USERID
把A、B、C这三个表换成你的表。如果不行再问我。
查询结果是这样的
1 liu 1 0 1
2 ggg 1 1 2
3 jjj 3 0 3
4 ddd 2 1 3
5 ffff 0 0 0
6 ccc 0 1 1
刚刚没有考虑到你是SQLSERVER 有可能不支持with 语句。也可以这么写:
SELECT C.USERNAME,
NVL(A.ACOUNT, 0) 表A数目,
NVL(B.BCOUNT, 0) 表B数目,
NVL(B.BCOUNT, 0) + NVL(A.ACOUNT, 0) 总数目
FROM C C
LEFT JOIN (SELECT B.USERID, COUNT(*) BCOUNT FROM B GROUP BY B.USERID) B
ON C.USERID = B.USERID
LEFT JOIN (SELECT A.USERID, COUNT(*) ACOUNT FROM A GROUP BY A.USERID) A
ON C.USERID = A.USERID;
WITH AA AS
(SELECT USERID, COUNT(USERID) ACOUNT FROM A GROUP BY USERID),
BB AS
(SELECT USERID, COUNT(USERID) BCOUNT FROM B GROUP BY USERID)
SELECT C.USERNAME,
NVL(AA.ACOUNT, 0) 表A数目,
NVL(BB.BCOUNT, 0) 表B数目,
NVL(AA.ACOUNT, 0) + NVL(BB.BCOUNT, 0) 总数目
FROM AA, BB, C
WHERE AA.USERID(+) = C.USERID
AND BB.USERID(+) = C.USERID
把A、B、C这三个表换成你的表。如果不行再问我。
查询结果是这样的
1 liu 1 0 1
2 ggg 1 1 2
3 jjj 3 0 3
4 ddd 2 1 3
5 ffff 0 0 0
6 ccc 0 1 1
刚刚没有考虑到你是SQLSERVER 有可能不支持with 语句。也可以这么写:
SELECT C.USERNAME,
NVL(A.ACOUNT, 0) 表A数目,
NVL(B.BCOUNT, 0) 表B数目,
NVL(B.BCOUNT, 0) + NVL(A.ACOUNT, 0) 总数目
FROM C C
LEFT JOIN (SELECT B.USERID, COUNT(*) BCOUNT FROM B GROUP BY B.USERID) B
ON C.USERID = B.USERID
LEFT JOIN (SELECT A.USERID, COUNT(*) ACOUNT FROM A GROUP BY A.USERID) A
ON C.USERID = A.USERID;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询