加入表后如何获得原始计数?

时间:2016-06-01 13:45:25

标签: sql-server

我正在尝试查找每个商店的产品数量/系统数量。表格如下所示:

Store
Id
100
200

Customer
Id      |    dealerId
1       |    100
2       |    200

System
Id  | CustomerId
20  | 2
30  | 2
40  | 2
50  | 1

Product
Id  |  SystemId
1000 | 20
2000 | 50

我想得到:

storeId  |  Number of systems  | number of products   |    average
100      |            1        |           1          |       1/1
200      |            3        |           1          |       1/3     

我写过这个查询。我得到了正确数量的产品,但系统数量搞砸了,因为我正在加入表格。有没有办法可以获得每个商店的系统总数?

SELECT
  s.Id as Store, 
  COUNT(Distinct SystemsIden) as NumOfSystems,
  COUNT(distinct ProductIden) as NumOfProduct,
  CAST(COUNT(distinct ProductIden)as float)/CAST(COUNT(Distinct SystemsIden) as 
  float) as average
FROM 
 Store s
  INNER JOIN
  (
  Select systemsiden,CustomerIden,ProductIden, Customer.StoreId as 
  storeiden from
 (
  select Product.ID as ProductIden, System.Id as systemsiden, System.customerId   as CustomerIden from product join Ssystem On System.Id = Product.SystemIdId
)
  table1 join Customer
  on Customer.Id = CustomerIden
)
  table2 On s.Id = storeiden
GROUP BY
  s.Id

2 个答案:

答案 0 :(得分:1)

不需要广泛的子查询用法,简单的外连接就足够了:

Exception

query results

答案 1 :(得分:0)

SELECT
  s.Id as Store, 
  COUNT(DISTINCT sys.id) as NumOfSystems,
  COUNT(DISTINCT p.id) as NumOfProduct,
  IFNULL(COUNT(DISTINCT p.id),0)/IFNULL(COUNT(Distinct sys.id),1) as average
FROM Store s
INNER JOIN Customer c
ON c.dealerId = s.id
INNER JOIN System sys
ON sys.customerId = c.id
INNER JOIN product p
ON sys.id=p.systemId
GROUP BY s.Id