SQL SELECT。涉及COUNT

时间:2013-08-09 09:30:58

标签: sql

所以我有3张桌子。一个包含IdName,第二个包含Id,其他一些与此处不相关,第三个表包含Id,{{1和table1Id(table1和table2对彼此一无所知)。我想table2Id以下内容。来自SELECT的{​​{1}}和Id以及来自Name的{​​{1}}来自table1的{​​{1}}。我怎样才能做到这一点。我对table2Id很新,所以任何帮助都会受到赞赏。提前致谢。如果需要,我可以提供更多细节。

2 个答案:

答案 0 :(得分:2)

SELECT
    Table1.ID,
    Table1.Name,
    COUNT(Table3.Table2ID) AS Table2IDCount
FROM
    Table1
    LEFT JOIN Table3 ON Table1.ID = Table3.Table1ID
GROUP BY
    Table1.ID,
    Table1.Name

答案 1 :(得分:0)

create table table1(id int, name nvarchar(20))

insert into table1 values(1, 'Value 1')
insert into table1 values(2, 'Value 2')
insert into table1 values(3, 'Value 3')

create table test1(id int, table1id int, table2id int)

insert into test1 values(1,1,1)
insert into test1 values(2,1,2)
insert into test1 values(3,1,3)
insert into test1 values(4,1,4)
insert into test1 values(5,1,5)
insert into test1 values(6,2,1)
insert into test1 values(7,2,2)
insert into test1 values(8,2,3)
insert into test1 values(9,2,4)
insert into test1 values(10,2,5)
insert into test1 values(11,3,1)
insert into test1 values(12,3,2)
insert into test1 values(13,3,3)
insert into test1 values(14,3,4)
insert into test1 values(15,3,5)


select n.id, n.name, count(distinct(table2id)) [Count]
from test1 t
inner join table1 n on (t.table1id = n.id)
group by n.id, n.name
order by 1