我有一个MySQL表
discount_vouchers
------------------
id
email
test_id
我的目标是列出使用给定电子邮件和GROUP BY中给定的test_id多次出现的所有优惠券:
GROUP BY email, test_id
HAVING count(*) >1
如何阅读此群组?
以下是一个例子:
discount_vouchers
------------------
1 1@test.com 20
2 1@test.com 10
3 1@test.com 20
4 2@test.com 30
我希望得到结果:
id email test_id count
1 1@test.com 20 2
2 1@test.com 10 1
3 1@test.com 20 2
4 2@test.com 30 2
答案 0 :(得分:0)
尝试类似以下内容
SELECT C2, counter from
(SELECT C2, COUNT(*) as counter FROM test.mytable
GROUP BY C2) as aggregation
WHERE counter > 1
如果不使用group by,您可以执行类似
的操作SELECT a.* ,
(SELECT count(*) FROM discount_vouchers b
WHERE a.email = b.email AND a.test_id = b.test_id) as count
FROM discount_vouchers a
答案 1 :(得分:-1)
这个怎么样? 使用子查询聚合,并使用其结果以丰富实际表:
SELECT `discount_vouchers`.*, `counts`.`count`
FROM `discount_vouchers`
INNER JOIN (SELECT `email`, `test_id`, Count(*) AS 'count'
FROM `discount_vouchers`) AS `counts`
ON `discount_vouchers`.`email` = `counts`.`email`
AND `discount_vouchers`.`test_id` = `counts`.`test_id`;