汇总SQL中列不同的所有行?

时间:2019-01-08 18:45:36

标签: sql sql-server sql-order-by

我有一张简单的桌子。

相关字段为:返回值和返回编号

因此,此表向我显示了所有退回的商品,此退回的退货编号以及此退回中所有商品的价值。

因此示例表可能看起来像这样

Line # | Item Number | Quantity Returned | Return Value | Return Number | Cust Order #

 1        789            1                   $40             123          456

 1        780            1                   $40             123          456

 1        780            1                   $20             124          456

我只希望它通过不同的返回数字来汇总所有返回值。例如,有两行返回编号为123,另一行返回编号为124。因此,应该取123之一并将其加到124,得到我的$ 60

我尝试过

    SUM((rh.Total_Value-rh.Freight_Charges)) OVER (PARTITION BY  rh.Customer_Purchase_Order_Number) as Total_Returned_Value 

    SUM((rh.Total_Value-rh.Freight_Charges)) OVER (PARTITION BY rh.Return_Number) as Total_Returned_Value 

    SUM((rh.Total_Value-rh.Freight_Charges)) OVER (PARTITION BY rh.Return_Number Order by rh.Customer_Purchase_Order_Number) as Total_Returned_Value 

    SUM((rh.Total_Value-rh.Freight_Charges)) OVER (PARTITION BY rh.Customer_Purchase_Order_Number Order by rh.Return_Number) as Total_Returned_Value 

这些似乎都不起作用,我觉得我对排序依据和分区依据并不太了解

这是我的完整代码

select  rh.Return_Number,
        rd.Odet_Line_Number, rd.Item_Number, rd.Color_Code, rd.Quantity_Returned,
        (rh.Total_Value-rh.Freight_Charges)as Returned_Value, rh.Remarks,
        SUM((rh.Total_Value-rh.Freight_Charges)) OVER (PARTITION BY /*rh.Return_Number Order by*/ rh.Customer_Purchase_Order_Number) as Total_Returned_Value 

from

[JMNYC-AMTDB].[AMTPLUS].[dbo].Returns_Header rh (nolock)

LEFT JOIN

[JMNYC-AMTDB].[AMTPLUS].[dbo].Returns_Detail rd (nolock) on rd.Return_Number = Rh.Return_number

WHERE rh.Customer_Purchase_Order_Number = @Shopify

1 个答案:

答案 0 :(得分:0)

每个标题可能有多个明细行,从而导致标题数据重复。如果您想按唯一的返回值求和,请首先在CTE中对标头进行计算,然后将结果加入到详细信息中,例如

with rh as 
 ( select -- assuming the rh.Return_Number is unique
          rh.Return_Number, 
         (rh.Total_Value-rh.Freight_Charges)as Returned_Value,
          rh.Remarks,
          SUM((rh.Total_Value-rh.Freight_Charges)) 
          OVER (PARTITION BY rh.Customer_Purchase_Order_Number) as Total_Returned_Value 
          -- don't know if this is the PARTITION you want, maybe none
   from

      [JMNYC-AMTDB].[AMTPLUS].[dbo].Returns_Header rh (nolock)
 )
select  rh.Return_Number,
        rd.Odet_Line_Number, rd.Item_Number, rd.Color_Code, rd.Quantity_Returned,
        rh.Returned_Value, rh.Remarks,
        rh.Total_Returned_Value 

from

   rh

LEFT JOIN

[JMNYC-AMTDB].[AMTPLUS].[dbo].Returns_Detail rd (nolock) on rd.Return_Number = Rh.Return_number

WHERE rh.Customer_Purchase_Order_Number = @Shopify