A
A
Alexander Shirobokov2015-10-02 23:15:59
MySQL
Alexander Shirobokov, 2015-10-02 23:15:59

How to count the number of unique records?

There is a table

CREATE TABLE `example` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
  `cid` BIGINT(20) NOT NULL,
  `date_time` DATETIME NOT NULL,
  PRIMARY KEY (`id`),
)

The task is to select records from a certain date and count how many of them are unique (for the entire table) by cid.
Found a way like this:
SELECT COUNT(DISTINCT сid)
FROM example
WHERE date_time > '2015-10-01 00:00:00'

but it counts unique records only in the selection.
How to be?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artur Polozov, 2015-10-02
@konrin

task is not entirely clear, but

SELECT t.cid, t.date_time, t2.cnt   
FROM example t
LEFT JOIN 
     (SELECT cid, COUNT(id) as cnt FROM example GROUP BY cid)  t2 ON  (t2.cid = t.cid)
WHERE date_time > '2015-10-01 00:00:00'
-- and t2.cnt = 1   -- только уникальные

R
Rsa97, 2015-10-03
@Rsa97

SELECT COUNT(*)
    FROM `example`
    GROUP BY `cid`
    HAVING MIN(`date_time`) > '2015-10-01 00:00:00'
        AND COUNT(`cid`) = 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question