0

我正在尝试创建一个查询,允许我查看所有客户的订单并使用 sql 添加一个附加列来查看客户欠的总金额。

以下代码检索正确的数据:

SELECT
    cu.FName + '  ' + cu.SName as 'Name', 
    cu.Address1 + ', ' + cu.Address2 + ', ' + cu.Address3 as 'Dispatch Address', 
    cu.PostCode, 
    co.DateOrdered, co.DateDispatched, 
    ma.MaterialName, 
    it.Quantity, 
    ma.Price as 'Total' 
FROM
    Customers cu 
LEFT JOIN 
    CustomerOrder co ON co.CustomerID = cu.CustomerID 
LEFT JOIN
    ItemOrder it ON it.OrderID = co.OrderID 
LEFT JOIN 
    Materials ma ON ma.MaterialID = it.MaterialID 

我现在需要在上面添加额外的代码来添加一列来显示客户欠的总金额,但是我卡住了,有人可以帮忙吗?

Date Order   |    Dispatch Date | Item  | QTY  |   Price | TOTAL AMOUNT FOR BOTH ROWS
2012-10-30   |    2012-11-25    | Bath  | 1    |   49.99 |  
2012-10-30   |    2012-11-25    | Sink  | 1    |   55.99 |
4

2 回答 2

0

尝试这个:

Select 
  cu.FName + '  ' + cu.SName as 'Name', 
  cu.Address1 + ', ' + cu.Address2 + ', ' + cu.Address3 as 'Dispatch Address', 
  cu.PostCode, 
  co.DateOrdered, co.DateDispatched, 
  ma.MaterialName, 
  it.Quantity, 
  ma.Price as 'Total' ,
  (it.Quantity * ma.Price) 'Owe amount'
from Customers cu 
left join CustomerOrder co on co.CustomerID = cu.CustomerID 
left join ItemOrder it on it.OrderID = co.OrderID 
left join Materials ma on ma.MaterialID = it.MaterialID 
于 2012-11-07T12:19:01.250 回答
0
SELECT
    cu.FName + '  ' + cu.SName as 'Name', 
    cu.Address1 + ', ' + cu.Address2 + ', ' + cu.Address3 as 'Dispatch Address', 
    cu.PostCode, 
    co.DateOrdered, co.DateDispatched, 
    ma.MaterialName, 
    it.Quantity, 
    ma.Price as 'Total',
    sum(it.Quantity * ma.Price) over (partition by cu.CustomerID) as TotalOwed
from Customers cu 
left join CustomerOrder co on co.CustomerID = cu.CustomerID 
left join ItemOrder it on it.OrderID = co.OrderID 
left join Materials ma on ma.MaterialID = it.MaterialID 
于 2012-11-07T12:22:08.390 回答