所以我有3张桌子。一个带有Id
and Name
,第二个带有Id
and 其他一些在这里不相关的东西,第三个带有它自己的东西Id
,table1Id
and table2Id
(table1 和 table2 彼此不知道任何事情)。我想要SELECT
以下。Id
和Name
从和stable1
的计数,从中将被分组。我怎样才能做到这一点。我很新,所以任何帮助将不胜感激。提前致谢。如果需要,我可以提供更多详细信息。table2Id
table3
table1Id
SQL
问问题
89 次
2 回答
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
于 2013-08-09T09:38:44.880 回答
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
于 2013-08-09T09:48:39.197 回答