使用此查询:
select C.CustomerID, P.ProductName, count(*) as Ordered
from Customers as C
join Orders as O on C.CustomerID = O.CustomerID
join [Order Details] as OD on O.OrderID = OD.OrderID
join Products as P on OD.ProductID = P.ProductID
group by C.CustomerID, P.ProductName
我可以选择客户购买的产品名称和订购
CustomerID|ProductName |Ordered
--------------------------------
ANTON |Alice Mutton|1
BERGS |Alice Mutton|1
BLONP |Alice Mutton|1
BOLID |Alice Mutton|1
BONAP |Alice Mutton|1
使用这个:
select P.ProductName, count(*) as Ordered
from Products as P
join [Order Details] as OD on P.ProductID = OD.ProductID
group by P.ProductName
我可以选择每件产品的订购次数:
ProductName |Ordered
-------------------------
Alice Mutton |37
Aniseed Syrup |12
Boston Crab Meat |41
Camembert Pierrot|51
Carnarvon Tigers |27
现在,我想将两个查询结合起来。我想看看单个客户订购了多少产品,以及该产品的订单总量是多少。我怎么能在一个查询中做到这一点?
答案 0 :(得分:1)
你在寻找这样的东西吗?:
select a.*, b.ordered from (
select C.CustomerID, P.ProductName, count(*) as Ordered
from Customers as C
join Orders as O on C.CustomerID = O.CustomerID
join [Order Details] as OD on O.OrderID = OD.OrderID
join Products as P on OD.ProductID = P.ProductID
group by C.CustomerID, P.ProductName)a
left join
(select P.ProductName, count(*) as Ordered
from Products as P
join [Order Details] as OD on P.ProductID = OD.ProductID
group by P.ProductName)b
on a.ProductName=b.ProductName
答案 1 :(得分:0)
对此:
select C.CustomerID, P.ProductName, count(*) as Ordered
from Customers as C
join Orders as O on C.CustomerID = O.CustomerID
join [Order Details] as OD on O.OrderID = OD.OrderID
join Products as P on OD.ProductID = P.ProductID
group by C.CustomerID, P.ProductName
添加如下内容:
union
select sum(0) as CustomerID, P.ProductName, count(*) as Ordered
from Orders as O
join [Order Details] as OD on O.OrderID = OD.OrderID
join Products as P on OD.ProductID = P.ProductID
group by P.ProductName
答案 2 :(得分:0)
基本上,您可以将总订单和客户订单的项目放入临时表,然后加入它们,如下所示。我选择了Name加入,但这可能需要调整,很难说。 我喜欢这些不仅仅是子查询,我认为它们通常更快,但你也可以在连接中进行子查询。类似的概念。这可能不会给你你想要的最终结果,但希望它会给你一个良好的开端。
cat
dog
rabbit