我想为每天发布超过一件事的用户获取所有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

最佳答案

这是解决方案

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一起使用。您可以检查自己的数据库)

关于mysql - MySQL查询选择每天有多个条目的所有用户,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17555576/

10-13 00:40