1

假设我们有桌子

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

查询 Count(customer)xCount(order) 对的最简单方法是什么?

例子

顾客:

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

命令

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

想要得到

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

2 回答 2

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小提琴

编辑

想起来,前面的说法可以简化成这样

        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

但这让我觉得我最初的陈述一开始就是错误的

于 2012-05-31T06:14:39.597 回答
0
select order.id, count(.CustomerId )
from Order order left join Customer customer on order.id = customer.CustomerId 
group by order.id
于 2012-05-31T06:24:35.413 回答