I have a table and I need to count all unique users on it. The schema of the table is:
idAccess | idClient | date | uid
1 | 12 | 2012-04-03 10:59 | 1234-1234-1234
2 | 13 | 2012-01-03 11.23 | 2345-2345-2345
3 | 12 | 2012-04-03 10:59 | 1234-1234-1234
4 | 12 | 2012-04-03 11:59 | 1234-1234-1234
5 | 12 | 2012-02-23 02:39 | 5788-5788-5687
6 | 12 | 2011-12-03 12:31 | asdf-1234-asdf
7 | 12 | 2011-10-13 13:36 | eeef-1234-eeee
8 | 15 | 2010-11-23 17:33 | qwer-EeQE-fhjh
This is the query:
Select
count(*) AS ct, count(DISTINCT(uid)) as users, YEAR(date) as ano
FROM
[AQUA_INTRANET].[dbo].[Accesos]
WHERE
idClient IN (12,13,15)
AND date> '01-01-2006 00:00' AND date< '04-02-2012 23:59'
GROUP BY
YEAR(date)
ORDER BY
year
and the result:
ct | users | year
5 | 6 | 2012
2 | 3 | 2011
1 | 1 | 2010
If I execute this query, I’m getting an wrong results, because the sum of the results is different from this other query:
Select
count(DISTINCT(uid)) as users
FROM
[AQUA_INTRANET].[dbo].[Accesos]
WHERE
idCliente IN (12,13,15)
AND fecha > '01-01-2006 00:00'
AND fecha < '04-02-2012 23:59'
and result is:
users
6
that is different if you sum the users column on the other query.
This happens sometimes, not always, but it’s very strange, because I’m having different values if I group by year or if I get the sum of all unique users.
I don’t know where is the problem, and I tried with different queries, but the result it wrong if I group by year.
One
uidcan have records that are in more than one year.Try these three queries
Also, note that I use
>= AND <to ensure no records ‘fall through the gaps’ or get double counted.