我有一个问题是显示客户总订单的总销售额(换句话说,价格总和)。使用以下SQL语句,我设法加入表'Order1','Order2'和'Customers'以达到必要的属性,以便为至少发出3个订单的客户显示正确的城市并将订单数量加到此:
SELECT c.CityName, SUM(o2.Orderquantity) AS 'Total sales amount'
FROM Order1 o1
INNER JOIN
(SELECT o1.CustomerNr
FROM Order1 o1
GROUP BY o1.CustomerNr
HAVING COUNT(o1.CustomerNr) >= 3)
AS a ON o1.CustomerNr = a.CustomerNr
INNER JOIN Order2 o2 ON o1.Ordernr = o2.Ordernr
INNER JOIN Customers c ON o1.CustomerNr = c.CustomerNr
GROUP BY c.CityName
我使用的表的结构如下:
所以,我想要的是能够展示至少已经订购了3个订单(迄今为止这么好)的客户所在的城市,以及这些客户的总销售额(而不是总订单数量)客户,有谁知道我怎么能根据上面的表格结构做到这一点?
示例数据: 表'客户'的示例数据:
- CustomerNr CityName:
- 01109 New York
- 01999 Los Angeles
- 08120 London
Sample data for 'Order1':
- Ordernr CustomerNr
- 1306 1109
- 1306 1109
- 1307 1109
Sample data for 'Order2':
- OrderNr ProductNr Order quantity:
- 1306 15-116 01109 3
- 1306 46-701 01109 2
- 1307 15-96 01109 1
- 1308 17-91 18208 1
(etc...)
Sample data for 'Products':
- ProductNr Price:
- 15-116 44.00
- 15-96 28.50
- 46-701 3000.00
etc...
正如您在'Order1'中所看到的,客户可以链接到几个订单,正如您在“产品”中看到的,每个产品都有其独特的产品和价格。正如您在'Order2'中看到的那样,客户1109(在这种情况下)购买了7个15-115产品和1个46-708产品,订购1306.但该客户还购买了15个产品中的2个产品在另一个顺序(1307)。这位来自纽约的客户共订购了2个订单,因此在这种情况下,结果应如下所示:
CityName,总销售额: 纽约,6160.50
答案 0 :(得分:0)
您只需在查询中加入 产品表
试试这个:
SELECT c.CityName, SUM(o2.quantity * p.Price) AS 'TotalSalesAmount'
FROM (SELECT DISTINCT Ordernr, CustomerNr FROM Order1) AS o1
INNER JOIN (SELECT o1.CustomerNr
FROM Order1 o1
GROUP BY o1.CustomerNr
HAVING COUNT(o1.CustomerNr) >= 3
) AS a ON o1.CustomerNr = a.CustomerNr
INNER JOIN Order2 o2 ON o1.Ordernr = o2.Ordernr
INNER JOIN Customers c ON o1.CustomerNr = c.CustomerNr
INNER JOIN Products P ON o2.ProductNr = P.ProductNr
GROUP BY c.CityName;