分组中的两个计数

时间:2016-05-31 16:33:19

标签: sql sql-server count

我想为每家商店找到该商店的产品数量/该商店的客户数量

Customer                 
Id | dealerId           
 1 | 10             
 2 | 11             
 3 | 10                     

Product             
Id   | CustomerId           
100  |  1               
200  |  3   
300  |  2       

store
Id
10
11

以上示例的结果将是:

StoreId | value

10      |  2/2
11      |  1/1

2 个答案:

答案 0 :(得分:1)

SELECT
  c.dealerID as Store, 
  COUNT(DISTINCT c.ID) as NumOfCustomers,
  COUNT(p.ID) as NumOfProducts
FROM 
  Customers C
  INNER JOIN
  Products p on p.CustomerId = c.Id
GROUP BY
  c.dealerID

答案 1 :(得分:0)

select S.Id AS StoreId, COUNT(p.Id) AS ProductId, COUNT(CAST.Id) AS CustomerId
from Store S 
    left join Customer C on C.dealerId = Scheduler.StoreId
    left join Product P on P.CustomerId = CAST.Id
group by S.Id
相关问题