根据初始选择从第二个表中选择计数

时间:2011-03-23 13:28:54

标签: tsql select

表1: AccountId,ReferenceId,Name,(许多其他列)

表2: AccountId,ReferenceId,(其他栏目)

如何选择以获得以下内容:

AccountId, ReferenceId, [Count(*) in Table2 where accountId and reference ID match.]
1, AB, 1
1, AC, 0
2, AD, 4
2, EF, 0

猜猜一个联接,但是这给了我价值,而不是计数? 尝试添加计数,但得到错误?

4 个答案:

答案 0 :(得分:2)

 SELECT T1.AccountId,
       T1.ReferenceId,
       COUNT(T2.ReferenceId) AS Cnt
FROM   Table1 T1
       LEFT JOIN Table2 T2
         ON T1.AccountId = T2.AccountId
            AND T1.ReferenceId = T2.ReferenceId
GROUP  BY T1.AccountId,
          T1.ReferenceId  

答案 1 :(得分:1)

类似的东西:

SELECT t1.AccountId, t1.ReferenceId, COUNT(t2.AccountId)
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.AccountId = t2.AccountId AND
                       t1.ReferenceId = t2.ReferenceId
GROUP BY t1.AccountId, t1.ReferenceId

应该有效。诀窍是按两个键值进行分组,以便您可以聚合其他值。在这种情况下,您只需要计算其他行的值(您也可以对按行分组的值求和或平均值。)。

答案 2 :(得分:0)

SELECT t1.AccountId, t1.ReferenceId, COUNT(t2.AccountId)
FROM Table1 t1 LEFT JOIN Table2 t2 
ON (t1.AccountId=t2.AccountId AND t1.ReferenceId=t2.ReferenceId)
GROUP BY Table1.AccountId, Table1.ReferenceId 

答案 3 :(得分:0)

示例数据

declare @tbl1 table (AccountId INT, ReferenceId int, Name varchar(20))
declare @tbl2 table (AccountId INT, ReferenceId int)

insert into @tbl1 select 1, 10, 'White'
insert into @tbl1 select 2, 20, 'Green'
insert into @tbl1 select 3, 30, 'Black'
insert into @tbl1 select 3, 40, 'Red'

insert into @tbl2 select 1, 10
insert into @tbl2 select 1, 10
insert into @tbl2 select 2, 20
insert into @tbl2 select 3, 30

查询

select t.AccountId, t.ReferenceId, t.Name
    ,(select COUNT(*) from @tbl2 t2 
            where t.AccountId = t2.AccountId 
            and t.ReferenceId = t.ReferenceId) as countt

    from @tbl1 t