我想知道如何获取所有数据行,其中给定事务(由TransactionID定义)的所有费用都是Price = 0.00。
因此,对于具有相同TransactionID的所有行,如果所有这些行中的Price为0.00,则返回具有该UserID,UserName和TransactionID的行。
*请注意,每笔交易可能有1个或多个费用,因此对于每个费用,要返回的行的价格必须等于0.00。
通过示例更容易解释......
鉴于此数据表:
+--------+----------+---------------+-------+-------+
| UserID | UserName | TransactionID | Price | FeeID |
+--------+----------+---------------+-------+-------+
| 1 | bill | 1111 | 0.00 | 1 |
| 1 | bill | 1111 | 7.00 | 2 |
| 2 | bob | 2222 | 0.00 | 2 |
| 3 | sarah | 3333 | 0.00 | 1 |
| 3 | sarah | 3333 | 0.00 | 2 |
| 4 | jill | 4444 | 8.00 | 1 |
| 5 | jack | 5555 | 3.00 | 1 |
| 5 | jack | 5555 | 7.00 | 2 |
| 1 | bill | 6666 | 0.00 | 1 |
| 1 | bill | 6666 | 0.00 | 2 |
| 1 | bill | 6666 | 0.00 | 3 |
+--------+----------+---------------+-------+-------+
查询应返回:
+--------+----------+---------------+
| UserID | UserName | TransactionID |
+--------+----------+---------------+
| 2 | bob | 2222 |
| 3 | sarah | 3333 |
| 1 | bill | 6666 |
+--------+----------+---------------+
谢谢!
答案 0 :(得分:2)
您的问题对我来说并不是很清楚,但从输出看起来您只需要使用having
条款:
select UserID, UserName, TransactionID
from table
group by UserID, UserName, TransactionID
having sum(price) = 0 and max(price) = 0
order by TransactionID
此查询为您提供与示例相同的结果。
having子句中的额外and max(price) = 0
确保总和不为0,因为存在相互抵消的值(如1,-1)。