Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL count distinct

I am trying to get the unique values out from a table, the table holds the following as a time log file:

id | time | code | user
1  | 7000 | xxxx | 1 
2  | 7000 | xxxx | 1
3  | 7500 | xxxx | 2
4  | 7000 | xxxx | 3

What I would like to know is how many unique users have used the code at time, e.g. 7000, it should say 2 but with the distinct I write I get 3

SELECT Time, COUNT(*) as total, Code
FROM dbo.AnalyticsPause
WHERE CODE = 'xxxx'
GROUP BY  id, Time, Code

Result:

time | Count | code 
7000 | 3     | xxxx
7500 | 1     | xxxx

where I would like to have

time | Count | code 
7000 | 2     | xxxx
7500 | 1     | xxxx

How would I be able to add a distinct on the id_user and still count all the time together

like image 607
Ewald Bos Avatar asked Jun 30 '18 08:06

Ewald Bos


People also ask

How count distinct rows in SQL Server?

We can use SQL Count Function to return the number of rows in the specified condition. The syntax of the SQL COUNT function: COUNT ([ALL | DISTINCT] expression); By default, SQL Server Count Function uses All keyword.

What is the difference between Count Count distinct and count (*) in SQL?

The simple answer is no – there is no difference at all. The COUNT(*) function counts the total rows in the table, including the NULL values.

How do you count unique records?

Syntax. SELECT COUNT(DISTINCT column) FROM table; This statement would count all the unique entries of the attribute column in the table . DISTINCT ensures that repeated entries are only counted once.

How do I count the number of distinct values of multiple columns in SQL?

How can I get distinct values of all columns in SQL? To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns.


1 Answers

count(*) counts the total number of rows (in the group). You should instead just count the distinct user:

SELECT   Time, COUNT(DISTINCT user) as total, Code
FROM     dbo.AnalyticsPause
WHERE    code = 'xxxx'
GROUP BY Time, Code
like image 74
Mureinik Avatar answered Oct 17 '22 14:10

Mureinik