2

表 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、计数(表 C 中的 ID)。样本输出将是

ID  COL1  COL2  CNT
1   abc   bcc    3
2   bcd   acc    2

有人可以帮我吗?表 A 和 B 使用 COl1 和 COL3 连接。

4

8 回答 8

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
于 2012-05-21T12:04:06.013 回答
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
于 2012-04-26T07:13:16.400 回答
1

为什么不通过 ID 加入表 A 和表 C 并获得计数?

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
于 2012-04-26T07:15:18.500 回答
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
于 2012-04-26T08:10:53.377 回答
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
于 2012-04-26T07:26:45.093 回答
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 
于 2012-04-26T07:15:18.827 回答
0

也许是这样的:

SELECT
    TableA.COL1,
    TableB.col2,
    (
        SELECT
            COUNT(*)
        FROM
            TableC
        WHERE
            TableC.ID=TableA.ID
    )
FROM
    TableA
    JOIN TableB
        ON TableA.COL1=TableB.col3
于 2012-04-26T07:15:41.360 回答
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
于 2012-04-26T07:15:43.120 回答