表B,表c。
表A有ID,col1
ID COL1
1 abc
2 bcd
表B具有col2,col3
col2 col3
bcc abc
acc bcd
表C具有ID,col4
ID col3
1 qwe
1 tre
1 uid
2 jkj
2 jwekj
现在,我需要选择ID,COL1,COL2,count(表C中的ID)。样本输出将是
ID COL1 COL2 CNT
1 abc bcc 3
2 bcd acc 2
有人可以帮我吗?表A和B使用COl1和COL3连接。
答案 0 :(得分:1)
select a.id
, max(a.col1)
, avg(b.col2)
, count(distinct c.ID)
from TableA a
join TableA b
on a.col1 = b.col3
left join
TableC c
on c.id = a.id
group by
a.id
答案 1 :(得分:1)
为什么不加入表A&表C按ID并得到计数?
SELECT TableA.ID, TableA.COL1, TableB.COL2, COUNT(TableC.*)
FROM TableA
INNER JOIN TableB ON TableB.COL3 = TableA.COL1
INNER JOIN TableC ON TableC.ID = TableA.ID
GROUP BY TableA.ID, TableA.COL1, TableB.COL2
ORDER BY TableA.ID, TableA.COL1, TableB.Col2
答案 2 :(得分:1)
select A.ID, A.Col1, B.Col2, Count(*) AS Cnt
from A
inner join B ON B.Col3 = A.Col1
left join C ON C.ID = A.ID
Group By A.ID, A.Col1, B.Col2
答案 3 :(得分:0)
SELECT A.ID, A.COL1, B.COL2, (SELECT COUNT(C.ID) FROM C) AS CNT
FROM A INNER JOIN B ON A.COL1=B.COL3
答案 4 :(得分:0)
也许是这样的:
SELECT
TableA.COL1,
TableB.col2,
(
SELECT
COUNT(*)
FROM
TableC
WHERE
TableC.ID=TableA.ID
)
FROM
TableA
JOIN TableB
ON TableA.COL1=TableB.col3
答案 5 :(得分:0)
Select
a.Id, a.col1, b.col2, count(c.*) As Cnt
From A as a
Inner Join B as b on a.col1 = b.col3
Inner Join C as c on a.Id = c.Id
Group By a.Id, a.col1, b.col2
答案 6 :(得分:0)
declare @A table(ID int, col1 varchar(50))
declare @B table(col2 varchar(50), col3 varchar(50))
declare @C table(ID int, col4 varchar(50))
INSERT INTO @A(ID, col1) values(1, 'abc')
INSERT INTO @A(ID, col1) values(2, 'bcd')
INSERT INTO @B(col2, col3) values('bcc' , 'abc')
INSERT INTO @B(col2, col3) values('acc' , 'bcd')
INSERT INTO @C(ID, col4) values('1' , 'qwe')
INSERT INTO @C(ID, col4) values('1' , 'tre')
INSERT INTO @C(ID, col4) values('1' , 'uid')
INSERT INTO @C(ID, col4) values('2' , 'jkj')
INSERT INTO @C(ID, col4) values('2' , 'jwekj')
-- The query
SELECT a.ID, a.col1, b.col2, (SELECT COUNT(c.ID) FROM @C c WHERE c.ID = a.ID) CNT
FROM @A a join @b b ON a.col1 = b.col3
答案 7 :(得分:0)
select A.iD, A.Col1,B.col2,
(select count(*) from tableC C where C.id=A.ID) as cnt
from tableA A join tableB B on A.col1=b.col3