SQL向查询添加其他列

时间:2012-11-07 12:14:16

标签: sql sql-server sql-server-2008 tsql

我正在尝试创建一个查询,允许我查看所有客户订单,并使用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 |

2 个答案:

答案 0 :(得分: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 

答案 1 :(得分: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