结合计数和链接表

时间:2014-05-20 10:53:20

标签: sql-server tsql

我有一个表ClientsID, name),一个表Items1ID, clientID, item1Name)和一个表Items2ID, ClientID, item2Name)< / p>

Clients

1, John
2, Miriam
3, Peter
4, Trude

Items1

1,1,exam1
2,1,exam2
3,2,exam3

Items2

1,1,test1
2,2,test2
3,4,test3

我想要完成的是一个查询,它将items1.IDitems2.ID汇总为一个数字,其中clientID = n

查询结果

clientID, total Items
=====================
1,3
2,2
3,0
4,1

这可能吗?

4 个答案:

答案 0 :(得分:1)

希望这也有效

SELECT c.id, 
       Count(item.itemname) AS TotalItem 
FROM   clients c 
       LEFT JOIN (SELECT id, 
                         clientid, 
                         item1name AS itemName 
                  FROM   item1 
                  UNION ALL 
                  SELECT id, 
                         clientid, 
                         item2name AS itemName 
                  FROM   item2) item 
              ON c.id = item.clientid 
GROUP  BY c.id 

答案 1 :(得分:0)

试试这个

Select c.id, count(a.*) + count(b.*)
From clients a
Left join items1 a on c.id = a.clientid
Left join items2 b on c.id = b.clientid
Group by c.id

答案 2 :(得分:0)

SQL-Server 2005 +

SELECT c.ID, i1.Cnt, i2.Cnt, i1.Cnt + i2.Cnt TotalCount
FROM Clients c
    CROSS APPLY (SELECT COUNT(*) Cnt FROM Items1 WHERE ClientID = c.ID) i1
    CROSS APPLY (SELECT COUNT(*) Cnt FROM Items2 WHERE ClientID = c.ID) i2

答案 3 :(得分:0)

此代码也可能有所帮助:

;with CTE as
(select ClientID,count(*) as ItemsCount
 from Items1
 group by ClientID
 union all
 select ClientID,count(*)
 from Items2
 group by ClientID)
select c.ID,isnull(sum(CTE.ItemsCount),0)
from Clients c
left join CTE on c.ID=CTE.ClientID
group by c.ID