如何查询计数(客户),计数(订单)对

时间:2012-05-31 06:11:09

标签: sql

假设我们有表

Order(customerId,orderDetails...) 
Customer(Id, customerDetails...)

查询Count(客户)xCount(订单)对的最简单方法是什么?

例如

客户:

ID | Name
---------
1  | Bob
2  | Ann

顺序

CustomerId | Address
--------------------
 1         | Block1
 1         | Block2
 1         | Block1
 2         | Home Address

想要获得

CustomerCount | OrderCount
--------------------------
     1        |    3
     1        |    1

2 个答案:

答案 0 :(得分:2)

怎么样

        SELECT DISTINCT COUNT(DISTINCT c.ID) AS CustomerCount
               , COUNT(*) AS OrderCount
        FROM   Customer AS c
               INNER JOIN [Order] AS o ON o.customerID = c.ID
        GROUP BY
              c.ID

SQL Fiddle

修改

想到它,之前的陈述可以简化为

        SELECT DISTINCT 1 AS CustomerCount
               , COUNT(*) AS OrderCount
        FROM   Customer AS c
               INNER JOIN [Order] AS o ON o.customerID = c.ID
        GROUP BY
              c.ID

但是这给我一种唠叨的感觉,我的初始陈述是错误的

答案 1 :(得分:0)

select order.id, count(.CustomerId )
from Order order left join Customer customer on order.id = customer.CustomerId 
group by order.id