我遇到了这个查询的语法问题。我试图从每个国家返回一家公司的最大总数。
表格如下:
Orders
Columns
OrderID
CustomerID
EmployeeID
OrderDate
RequiredDate
OrderDetails
Columns
OrderID
ProductID
UnitPrice
Quantity
Products
Columns
ProductID
ProductName
QuantityPerUnit
UnitPrice
Customers
Columns
CustomerID
CompanyName
ContactName
Country
我尝试了以下内容:
SELECT
T1.Country,
CompanyName,
T1.OrderSum
FROM
(SELECT
C.Country,
C.CompanyName,
SUM(UnitPrice * Quantity) AS OrderSum
FROM Customers C
JOIN Orders O
ON C.CustomerID = O.CustomerID
JOIN OrderDetails D
ON D.OrderID = O.OrderID
GROUP BY C.Country) T1
JOIN
-- TOP PAYMENT TOTALS BY COUNTRY
(SELECT COUNTRY,
MAX(OrderSum) AS OrderSum
FROM
-- PAYMENT TOTALS BY CUSTOMER
(SELECT C.Country,
C.CompanyName,
SUM(UnitPrice * Quantity) AS OrderSum
FROM Customers C
JOIN Orders O1
ON O1.CustomerID = C.CustomerID
JOIN OrderDetails D1
ON D1.OrderID = O1.OrderID
GROUP BY C.COUNTRY, C.CompanyName) T2
GROUP BY COUNTRY) T3
ON T1.COUNTRY = T3.COUNTRY
AND T1.OrderSum = T3.OrderSum
ORDER BY Country;
此查询仅返回三个国家/地区:
Ireland Hungry Owl All-Night Grocers 57317.3900
Norway Sant Gourmet 5735.1500
Poland Wolski Zajazd 3531.9500
但是,我试过的这个查询会返回所有国家/地区,但我不确定它是否正确,因为我没有包含“' max'像我在上一个查询中所做的那样:
SELECT
T1.Country,
CompanyName,
T1.OrderSum
FROM
(SELECT
C.Country,
C.CompanyName,
SUM(UnitPrice * Quantity) AS OrderSum
FROM Customers C
JOIN Orders O
ON C.CustomerID = O.CustomerID
JOIN OrderDetails D
ON D.OrderID = O.OrderID
GROUP BY C.CompanyName) T1
GROUP By Country
ORDER BY Country;
我也不确定我是否正确计算订单总数,这可能是我的错误。但我试图找到总数最大的每个国家的公司。 对不起,所有的文字。
答案 0 :(得分:1)
以下查询仅列出每个国家/地区订单总数最大的公司:
SELECT A.Country, A.CompanyName, A.OrderSum
FROM (
SELECT
C.Country,
C.CompanyName,
SUM(D.UnitPrice * D.Quantity) AS OrderSum
FROM Customers C
JOIN Orders O ON C.CustomerID = O.CustomerID
JOIN OrderDetails D ON D.OrderID = O.OrderID
GROUP BY
C.Country, C.CustomerID
) A
JOIN (
SELECT
S.Country, MAX(S.OrderSum) as MaxSum
FROM (
SELECT
C.Country,
C.CompanyName,
SUM(D.UnitPrice * D.Quantity) AS OrderSum
FROM Customers C
JOIN Orders O ON C.CustomerID = O.CustomerID
JOIN OrderDetails D ON D.OrderID = O.OrderID
GROUP BY
C.Country, C.CustomerID
) S
GROUP BY
S.Country
) B ON A.Country = B.Country
WHERE
A.Country = B.Country AND
A.OrderSum = B.MaxSum
ORDER BY
A.Country, A.CompanyName
;
[UPDATE]
请注意,上述SQL遵循列出的查询中计算OrderSum
的方式。鉴于表格Products
包含QuantityPerUnit
和UnitPrice
,我怀疑您的OrderSum
也应该乘以QuantityPerUnit
- 在这种情况下,您可以使用OrderSum
需要修改{{1}}的数学。