SELECT COUNT(*)
FROM (
SELECT l.userid
FROM (
SELECT DISTINCT userid, CAST(tmstmp AS DATE)
FROM logins
WHERE type <> 'mobile'
AND tmstmp BETWEEN '2013-04-21' AND '2014-04-21') l
GROUP BY l.userid
HAVING count(*) > 5) t;
您好,我可以就如何清理此查询提出建议......也许是一种删除其中一个嵌套表的聪明方法?提前谢谢。
答案 0 :(得分:0)
听起来您正在寻找另一个aggregate
内的aggregate
。我认为这是使用单个子查询的最佳选择:
SELECT COUNT(*)
FROM (
SELECT userid
FROM logins
WHERE type <> 'mobile' AND tmstmp BETWEEN '2013-04-21' AND '2014-04-21'
GROUP BY userid
HAVING count(distinct CAST(tmstmp AS DATE)) > 5
) t
答案 1 :(得分:0)
使用WITH将使其更具可读性:
WITH matching_users AS (
SELECT userid
FROM logins
WHERE type <> 'mobile' AND tmstmp BETWEEN '2013-04-21' AND '2014-04-21'
GROUP BY userid
HAVING count(distinct CAST(tmstmp AS DATE)) > 5
)
SELECT count(*) FROM matching_users
答案 2 :(得分:0)
这是一种方法:
SELECT COUNT(*)
FROM (
SELECT userid, COUNT(DISTINCT CAST(tmstmp AS DATE)) as number_of_logins
FROM logins l
WHERE type <> 'mobile' AND tmstmp BETWEEN '2013-04-21' AND '2014-04-21'
GROUP BY l.userid
HAVING number_of_logins > 5) t
这会获取登录日期的不同日期,并仅计算超过5的用户