好吧,这个真的很棘手:D
我有一张 table
bills_products:
- bill_id - product_id - action -
| 1 | 4 | add |
| 1 | 5 | add |
| 2 | 4 | remove |
| 2 | 1 | add |
| 3 | 4 | add |
如您所见,ID 为 4 的产品在账单 1 中添加,然后在账单 2 中删除,并在账单 3 中再次添加
所有账单都属于一个账单组。但为简单起见,我们假设所有账单都在同一组中。
现在我需要一个 SQL 查询来显示当前添加到该组的所有产品。
在这个例子中,这将是 5、1 和 4。如果我们删除 ID 为 3 的账单,那将是 5 和 1
我已经尝试用 DISTINCT 做到这一点,但它不够强大,或者我做错了。
最佳答案
这似乎至少在 SQL Server 中有效:
select product_id
from (
select product_id,
sum((case when action='add' then 1 else -1 end)) as number
from bills_products
group by product_id
) as counts
where number > 0
关于sql - 高级不同 SQL 查询的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1916226/