如何获取具有重复列的行数?

时间:2011-10-05 10:41:44

标签: mysql

让我们说以下是我的表

id | name | topic | reply
...
1 | user1 | 00001 | yes              ## replied on topic 00001
2 | user2 | 00002 | yes              ** replied on topic 00002
3 | user1 | 00001 | yes              ## replied on topic 00001
4 | user5 | 00001 | no
5 | user1 | 00001 | yes              ## replied on topic 00001
6 | user1 | 00002 | no
7 | user2 | 00002 | yes              ** replied on topic 00002
8 | user3 | 00001 | no
9 | user4 | 00002 | yes

想象一下,这是一个主题表。只有user1和user多次回复一个主题(主题00001和00002) 如何选择多次回复某个主题的用户数,该用户应从5

返回2

2 个答案:

答案 0 :(得分:3)

这将为您提供在主题上多次回复的用户数量:

SELECT COUNT(DISTINCT name)
FROM (
    SELECT name
    FROM  yourtable
    WHERE reply = 'yes'
    GROUP BY name, topic
    HAVING COUNT(*) > 1
) T1

答案 1 :(得分:3)

首先,您需要计算每个主题每个用户的回复数量,然后计算对任何主题都有多个回复的不同用户的数量。

SELECT COUNT(DISTINCT name) FROM (
    SELECT name, topic, count(*) replies
    FROM table
    WHERE reply = 'yes'
    GROUP BY name, topic
) a
WHERE replies > 1