Access SQL:Having子句

时间:2017-08-28 14:19:57

标签: sql ms-access

我正在努力获得重复率大于1的用户(例如,在Excel中我会使用countif公式来执行此操作)。

我正在使用Ms-access(2016)并且似乎无法使用此功能。以下查询的结果为userName和Repeat Rate的计数提供了相同的结果。

SELECT host, department, count([userName]) AS ['Distinct Users'], sum(Logins) AS ['Total Logins'], count([Repeat Rate]) AS ['Repeat Users']
FROM (SELECT DISTINCT department, [userName], host,[Repeat Rate], Logins FROM Sheet1)  AS x
GROUP BY department, host
ORDER BY host, department,
HAVING COUNT([Repeat Rate]) > 1;

非常感谢任何帮助,谢谢!

编辑:

+------+----------+------------+-------------+--+
| host | username | Department | Repeat Rate |  |
+------+----------+------------+-------------+--+
| x    | Kyle     | D1         |           1 |  |
| x    | Max      | D1         |           4 |  |
| x    | Will     | D1         |           2 |  |
| x    | Will     | D1         |           2 |  |
+------+----------+------------+-------------+--+

以上表为例,我希望对于D1部门的主机x说,有3个不同的用户,2个用户的重复率大于1。

+------+------------+----------------+-------------+
| host | Department | Distinct Users | Repeat Rate |
+------+------------+----------------+-------------+
| x    | D1         |              3 |           2 |
+------+------------+----------------+-------------+

3 个答案:

答案 0 :(得分:2)

试试这个

SELECT host, department, count([userName]) AS ['Distinct Users'], sum(IIF([Repeat Rate]>1,1,0)) AS ['Repeat Users']
FROM (SELECT DISTINCT host, department, [userName], [Repeat Rate] FROM Sheet1)  AS x
GROUP BY department, host;

答案 1 :(得分:1)

您可以尝试这样的事情:

SELECT x.host, x.department, max(users.unique_users) AS ['Distinct Users'], 
    sum(Logins) AS ['Total Logins'], max(repeats.unique_repeats) AS ['Repeat Users']
FROM (SELECT DISTINCT department, [userName], host,[Repeat Rate], Logins FROM Sheet1)  AS x
left join (select host, department, count(userName) as unique_users from (select distinct 
    host, department, [userName] from Sheet1)) as users on users.host = x.host and 
    users.department = x.department
left join (select host, department, count(userName) as unique_repeats 
    from (select distinct host, department, [userName] from Sheet1 where [Repeat Rate] > 1)) 
        as repeats on users.host = x.host and users.department = x.department
GROUP BY department, host
ORDER BY host, department;

在Access SQL中计算唯一值很困难。通常你会使用count(distinct var)作为另一个建议,但是你无法使用。

答案 2 :(得分:0)

我不确定您在帖子第一部分中显示的联接,但是,仅考虑您的示例,以下查询似乎可以解决您的问题


SELECT HOST, DEPARTMENT, SUM(DISTINCT_USER) AS DISTINCT_USER, MAX(CNT) AS REPEAT_RATE
FROM (
    SELECT HOST, DEPARTMENT, COUNT(DISTINCT USERNAME) AS DISTINCT_USER, REPEAT_RATE, COUNT(*) AS CNT
    FROM 
    GROUP BY HOST, DEPARTMENT, REPEAT_RATE
) A
GROUP BY HOST, DEPARTMENT