Do aggregate MySQL functions always return a single row?

前端 未结 1 1478
野趣味
野趣味 2020-12-21 01:44

I\'m sorry if this is really basic, but:

I feel at some point I didn\'t have this issue, and now I am, so either I was doing something totally different before or my

相关标签:
1条回答
  • 2020-12-21 02:13

    You need to use GROUP BY as such to get your desired result:

    SELECT
    order_id,
    part_id,
    SUM(cost) AS total
    FROM orders 
    WHERE order_date BETWEEN xxx AND yyy
    GROUP BY order_id, part_id
    

    This will group your results. Note that since I assume that order_id and part_id is a compound PK, SUM(cost) in the above will probably be = cost (since you a grouping by a combination of two fields which is guarantied to be unique. The correlated subquery below will overcome this limitation).

    Any non-aggregate rows fetched needs to be specified in the GROUP BY row.

    For more information, you can read a tutorial about GROUP BY here:

    MySQL Tutorial - Group By


    EDIT: If you want to use a column as both aggregate and non-aggregate, or if you need to desegregate your groups, you will need to use a subquery as such:

    SELECT
    or1.order_id,
    or1.cost,
    or1.part_id,
    (
      SELECT SUM(cost)
      FROM orders or2
      WHERE or1.order_id = or2.order_id
      GROUP BY or2.order_id
    ) AS total
    FROM orders or1
    WHERE or1.order_date BETWEEN xxx AND yyy
    
    0 讨论(0)
提交回复
热议问题