SQL Server - GROUP BY on one column

后端 未结 5 1969
感情败类
感情败类 2020-12-31 04:48

I\'m trying to get orders from an orderview. In my view I do have some rows with exactly the same values, but I want to group these values on orderid and take the sum of the

5条回答
  •  Happy的楠姐
    2020-12-31 05:36

    You could use a CTE with SUM(Quantity)OVER(PARTITION BY Order_id) + ROW_NUMBER to pick out the desired row from the order-group:

    WITH cte 
         AS (SELECT order_id, 
                    customer_id, 
                    article_id, 
                    delivery_date, 
                    quantity=Sum(quantity) 
                               OVER( 
                                 partition BY order_id), 
                    rn = Row_number() 
                           OVER( 
                             partition BY order_id 
                             ORDER BY delivery_date ASC) 
             FROM   orders) 
    SELECT order_id, 
           customer_id, 
           article_id, 
           delivery_date, 
           quantity 
    FROM   cte 
    WHERE  rn = 1 
    

    DEMO

    However, your desired result seems to be incorrect (question edited)

    This is my result:

    ORDER_ID    CUSTOMER_ID ARTICLE_ID  DELIVERY_DATE   QUANTITY
    PR10.001    11          20.001a         17-04-2013  3
    PR13.001    15          41.022b         19-04-2013  2
    

提交回复
热议问题