TSQL - SQL Server 2014 - 基于不同参数的总和

时间:2017-11-22 02:14:47

标签: sql sql-server

我有一张包含销售详情的表格。

买方可以购买多件商品并一起付款:在这种情况下,OrderID对所有商品都相同,PaymentAmountPaymentID

但是可能会分两次付款,在这种情况下会有不同的PaymentID(付款金额可能相同)。

我需要检查运费是否正确计算,PaymentAmountsQuantity*Price之间的差异

相关栏目是:

| SaleID | OrderID | Quantity | Price | PaymentAmount | PaymentID | Shippingcost |
|  0001  |   001   |    3     |  3.50 |      13.50    |    BT123  |    3.00      |
|  0002  |   002   |    1     |  1.50 |      13.50    |    BB331  |    5.50      |
|  0003  |   002   |    5     |  2.00 |      13.50    |    BB331  |    5.50      |
|  0004  |   002   |    2     |  5.00 |      13.50    |    BB332  |    5.50      |
|  0005  |   003   |    1     |  3.00 |      12.50    |    BV444  |    4.00      |
|  0006  |   003   |    1     |  5.50 |      12.50    |    BV444  |    4.00      |

因此同样

  

订单ID

我需要将具有不同PaymentID的付款金额相加,我必须总结所有数量和价格:

因此,对于OrderID 002,我希望:

TotalPayments 27.00  
TotalGoods    21.50  
ShippingCosts  5.50 

到目前为止,我的解决方案看起来像这样:

declare @OrderID nvarchar(10)='0002'

select distinct
    paymentAmount,
    sum (quantitypurchased*currentprice) over (partition by OID) TotalGoods
from 
    Sales s
where 
    OrderID = @OrderID

declare @OrderID nvarchar(10) = '0002'

select distinct
    sum(paymentAmount) over () TotalPayments,
    sum (quantitypurchased * currentprice) over (partition by OID) TotalGoods
from 
    Sales s
where 
    OrderID = @OrderID

问题在于第一个解决方案不会返回总计,尽管有正确的数字来计算它。

但主要问题是返回超过1行,而对于进一步处理,我需要将总货物和总付款放在一行

虽然第二行返回一行中的总数,但TotalPayments错误,因为值的添加次数超过1次。

而且我很确定这可以通过更多的技能“轻松”实现。

能帮到一点吗?

2 个答案:

答案 0 :(得分:1)

我认为窗口函数可以帮助您隔离需要参与计算的行:

select s.orderid,
       sum(case when seqnum = 1 then paymentamount else 0 end) as totalpayments,
       sum(quantity * price) as totalprice,
       max(shippingcost) as shippingcost
from (select s.*,
             row_number() over (partition by s.orderid, s.paymentid order by saleid) as seqnum
      from sales s
     ) s
group by s.orderid;

答案 1 :(得分:0)

我提出了与戈登答案相同的逻辑,但我使用了CTE。

;With CTE
As
(
    Select 
        OrderID,
        Quantity,
        Price,
        PaymentAmount,
        ShippingCost,
        ROW_NUMBER() Over(Partition By OrderID, PaymentID Order By OrderID) As RowNum
    From Sales
)
Select 
    OrderID,
    Sum(Case When RowNum = 1 Then PaymentAmount End) As TotalPayments,
    Sum(Quantity * Price) As TotalCosts,
    Max(ShippingCost) As ShippingCost
From CTE
Group By OrderID
Order By OrderID;