我有下表:
Transaction_ID int(9) NO PRI NULL auto_increment
Datetime date NO NULL
Giver_ID int(9) NO NULL
Recipient_ID int(9) NO NULL
Points int(4) NO NULL
Category_ID int(3) NO NULL
Reason text NO NULL
显然,我已经成功地为“行为周”奖励了一些学生的双倍积分。
我想要一个此transactions
表中所有行的列表,其中单个用户(Recipient_ID
)与Category_ID = 16
有多个交易。
每个Recipient ID
只应与Category_ID = 16
进行一次交易。
例如,如果我有......
54784 2012-02-01 138573 137444 100 16 You have done very well in Behaviour Week! Because...
55040 2012-02-01 138573 132629 100 16 You have done very well in Behaviour Week! Because...
这是两个独立的用户,这很好。
但是,如果我找到......
54784 2012-02-01 138573 137444 100 16 You have done very well in Behaviour Week! Because...
55040 2012-02-01 138573 137444 100 16 You have done very well in Behaviour Week! Because...
然后我犯了一个错误,我需要删除其中一行。
有人可以建议一个查询,列出所有这些可能不正确的交易吗?我更喜欢他们只是为了“选择”,以便我可以手动检查而不是盲目地删除。
答案 0 :(得分:2)
要查找类别16中具有多于1个事务的收件人ID,您可以使用以下内容:
select Recipient_ID,
Count(Transaction_ID) as [Transactions]
from myTable
where Category_ID = 16
group by Recipient_ID
having Count(Transaction_ID) > 1
如果您想真正放心,请删除Having子句:
select Recipient_ID,
Count(Transaction_ID) as [Transactions]
from myTable
where Category_ID = 16
group by Recipient_ID
然后,您可以查看针对每个收件人ID的交易数量,并确保每个
确实为1答案 1 :(得分:2)
您可以使用分组并拥有:
select count (transaction_id), recipient_id
from thetable
where category_id = 16
group by recipient_id
having count(transaction_id) > 1
having
子句与where
子句非常相似,但在分组发生后,它在行上运行。换句话说,where
是一个预分组过滤器,having
是一个后分组过滤器。
答案 2 :(得分:1)
select Recipient_ID, COUNT(*)
from transactions
where Category_ID = 16
group by Recipient_ID
having COUNT(*) > 1
答案 3 :(得分:0)
尝试
SELECT * FROM transactions WHERE category_id = 16 GROUP BY recipient_id HAVING COUNT(*)>1
这将仅显示具有多个这些条目的用户