SQL Server - GROUP BY on one column

后端 未结 5 1976
感情败类
感情败类 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条回答
  •  无人及你
    2020-12-31 05:44

    Assuming the other columns are functionally dependent on the grouping column, the simplest answers are either

    a. Group by the other columns as well:

    SELECT Order_id, Customer_id, Article_id, Delivery_date, sum(Quantity)
    FROM Orders
    GROUP BY Order_id, Customer_id, Article_id, Delivery_date
    

    or

    b. Use an aggregate function such as max:

    SELECT Order_id, max(Customer_id), max(Article_id), max(Delivery_date), sum(Quantity)
    FROM Orders
    GROUP BY Order_id
    

    My personal preference is the second approach, as I think it is clearer than the first in indicating which items are actually required for grouping, as opposed to which are merely being grouped to get round the ungrouped/unaggregated column problem.

提交回复
热议问题