How to get rows having sum equal to given value

后端 未结 4 922
南旧
南旧 2020-12-19 10:19

There is table contain

ID     Qty
----------
1       2
2       4
3       1
4       5

Now if i had to choose rows where sum of Qty equals to

4条回答
  •  粉色の甜心
    2020-12-19 11:06

    If you want it to be exactly always three numbers that add to 10, then this

    SELECT
      *
    FROM 
      MyTable t1
      JOIN
      MyTable t2 ON t1.ID <> t2.ID 
      JOIN
      MyTable t3 ON t1.ID <> t3.ID AND t2.ID <> t3.ID
    WHERE
      t1.Qty + t2.Qty + t3.Qty = 10
    

    If you want 2 or 4 or 5 numbers then you can't really do it in SQL

    Edit:

    • Updated to ignore by ID not Qty
    • And again: If you want 2 or 4 or 5 numbers then you can't really do it in SQL

提交回复
热议问题