MySQL查询,选择每天有多个条目的所有用户

时间:2013-07-09 18:28:52

标签: mysql database

我希望获得每天发布多件事的用户的所有USER_ID,

我最初尝试过这个

    SELECT USER_ID, count(DISTINCT cast(POSTING_DATE as DATE))
    AS NUM_DAYS_OF_DUPLICATES FROM POSTING_TABLE
    WHERE USER_ID IN
        (SELECT USER_ID FROM POSTING_TABLE
        GROUP BY CAST(POSTING_DATE AS DATE) HAVING count(*) >= 2)
    GROUP BY USER_ID ORDER BY NUM_DAYS_OF_DUPLICATES DESC;

然后这适用于特定的USER_ID

    SELECT USER_ID FROM POSTING_TABLE WHERE USER_ID = 30 
    GROUP BY cast(POSTING_DATE AS DATE) 
    HAVING count(cast(POSTING_DATE AS DATE)) > 1

上面给出了正确的结果,但是当我在整个表上运行查询而没有指定USER_ID时,它没有。

例如,

表结构USER_ID,POSTING_DATE ...

    USER_ID POSTING_DATE
    1       10-10-13
    1       10-10-13
    1       10-12-13
    1       10-12-13
    2       10-10-13
    2       10-10-13
    3       10-10-13
    4       10-12-13

结果会给我什么

    USER_ID  NUM_DAYS_WITH_MORE_THAN_ONE_POSTING
    1        2
    2        1
    3        0
    4        0

此外,如果我们可以省略0的

1 个答案:

答案 0 :(得分:1)

这是解决方案

select x.user_id, count(x.num_days)
from
(
select USER_ID, COUNT(USER_ID) AS NUM_DAYS
from data1 
group by user_id, posting_date
having count(user_id) > 1
) x
group by 1

Working SQL Fiddle

(为了简单起见,我使用varchar作为日期,但它也适用于date。你可以查看你自己的数据库)