1

我有两个表需要为其创建查询。我相信我也需要加入他们。

我需要从我的表中获取客户的CustomerName和,但我还需要查询以显示客户下的所有订单的总美元金额。因此,如果客户今年总共花费了 300 美元,那么这 300 美元就是我想要实现的输出。AddressCustomer

我有一个名为的表Order Details,它使用一个OrderID与 a 相关联的表,并且表中CustomerIDunitpricequantityOrder Details。我试图弄清楚如何将这些组合起来,但我快疯了。

我已经尝试过至少从订单中获取总数,但我肯定有语法错误:

SELECT unitprice, 
       quantity 
FROM   [Order details] (unitprice * quantity) AS Totalorders, 
       from [Order Details] 
WHERE  orderid > 0 

这也没有任何运气:

SELECT customers.companyname                                AS 'Company Name', 
       customers.address                                    AS 'Address', 
       [order details].unitprice * [order details].quantity AS 'Orders' 
FROM   customers 
       LEFT JOIN orders 
              ON customers.customerid = orders.customerid 
ORDER  BY customers.companyname, 
          customers.address, 
          orders 

谢谢

4

2 回答 2

0

if it s one-to-many relationship, your query will look something like:

SELECT
Customers.CompanyName AS 'Company Name',
Customers.Address AS 'Address',
SUM(O.Unitprice * O.quantity) as 'Orders'
FROM Customers
LEFT JOIN [Order Details] O
ON Customers.CustomerID = O.CustomerID
GROUP BY Customers.CompanyName, Customers.Address
ORDER BY Customers.CompanyName, Customers.Address
于 2013-01-11T02:40:27.907 回答
0

You need to join in the order details and do a group by aggregation:

SELECT c.CompanyName AS "Company Name",
       c.Address AS "Address",
       sum(od.Unitprice * od.quantity) as "Orders"
FROM Customers c LEFT JOIN
     Orders o
     ON c.CustomerID = o.CustomerID left join
     [Order Details] od
     on od.orderid = o.orderid
GROUP BY c.CompanyName, c.Address
ORDER BY c.CompanyName, c.Address

In addition, I made some stylistic changes. I added aliases to the table names. I find it much easier to read c.CompanyName rather than Customers.CompanyName. I changed the delimiter on the column aliases to use double quotes rather than single quotes. I associate single quotes with string constants inside the statement.

于 2013-01-11T02:40:30.170 回答