我该如何选择
| Customer_name | Num_of_AllTime_Orders | Num_of_different_Products_That_Customer_Ordered |
当每个数据来自不同表时作为表?
我试图计算客户数量,加入表格并进行分组...但是没有运气。
SELECT CompanyName, count(Customer_ID) from dbo.CUSTOMERS join dbo.ORDERS on CUSTOMERS.Customer_ID=ORDERS.CustomerID
Customers_Table:
CustomerID | Customer_Name
Orders_Table:
OrderID| Customer_ID
Order_Detail_Table:
OrderID| Product_ID |
我希望具有这些列的表的输出:
1. Customer_Name
2. Num_of_AllTime_Orders - how many orders that costumer made?
3. Num_of_different_Products_That_Customer_Ordered - how many different products that customer ordered?
答案 0 :(得分:-1)
Select CUSTOMERS.Customer_Name
,count(distinct ORDERS.OrderID) as Num_of_AllTime_Orders
,count(distinct Order_Detail_Table.Product_ID) as Num_of_different_Products_That_Customer_Ordered
from dbo.CUSTOMERS
join dbo.ORDERS on CUSTOMERS.CustomerID = ORDERS.Customer_ID
join dbo.Order_Detail_Table on ORDERS.OrderID = Order_Detail_Table.OrderID
group by CUSTOMERS.Customer_Name
答案 1 :(得分:-1)
SELECT Company_Name = C.CompanyName, NumOfOrders = COUNT (DISTINCT O.OrderID), NumOfProducts = COUNT (DISTINCT OD.ProductID)
FROM dbo.CUSTOMERS AS C JOIN ORDERS AS O ON C.Customer_ID=O.CustomerID JOIN ORDERDETAILS AS OD ON OD.OrderID=O.OrderID
GROUP BY C.CompanyName
ORDER BY 1