2

大家好,我有一个 mysql 数据库表,如下所示

      date                  id                   name 

   2012-09-18               1                     A
   2012-09-18               2                     B
   2012-09-18               1                     C
   2012-09-17               1                     D
   2012-09-17               1                     A
   2012-09-17               2                     A
   2012-09-16               1                     A
   2012-09-16               1                     E

ID = 1 的期望结果

     DATE                  UNIQUES
   2012-09-18               1      
   2012-09-17               1  
   2012-09-16               2  

文字描述

我想计算按日期分组的每个 id 的唯一名称。例如。9月16日 uniques =2 因为 A、E 在此表中 9 月 16 日之前不会出现。9月17日 uniques =1,因为 D 在此表中 9 月 17 日之前未出现,而 A 已在 9 月 16 日出现。

4

3 回答 3

2
SELECT
`date`,
SUM(CASE WHEN EXISTS(SELECT 1 FROM yourTable u2 WHERE u1.date > u2.date AND u1.name = u2.name) THEN 0 ELSE 1 END) AS uniques
FROM
yourTable u1
WHERE id = 1
GROUP BY 1
于 2012-09-18T09:07:41.780 回答
0
create table t (d date, id integer, name varchar(30));

insert into t (d, id, name) values
('2012-09-18', 1, 'A'),
('2012-09-18', 2, 'B'),
('2012-09-18', 1, 'C'),
('2012-09-17', 1, 'D'),
('2012-09-17', 1, 'A'),
('2012-09-17', 2, 'A'),
('2012-09-16', 1, 'A'),
('2012-09-16', 1, 'E')
;

select d as `DATE`, count(*) as UNIQUES
from (
    select name, min(d) as d
    from t
    where id = 1
    group by name
    ) s
group by `DATE`
order by `DATE` desc
;
+------------+---------+
| DATE       | UNIQUES |
+------------+---------+
| 2012-09-18 |       1 |
| 2012-09-17 |       1 |
| 2012-09-16 |       2 |
+------------+---------+
于 2012-09-18T12:40:22.603 回答
-1

我的建议:

SELECT `date`,
       Sum(CASE
             WHEN so_far = 1 THEN 1
             ELSE 0
           end) AS UNIQUES
FROM   (SELECT a.`date`,
               a.id,
               a.name,
               Count(DISTINCT b.`date`) AS so_far
        FROM   srctable AS a
               JOIN srctable AS b
                 ON ( a.id = b.id
                      AND a.name = b.name
                      AND a.`date` >= b.`date` )
        GROUP  BY a.`date`,
                  a.id,
                  a.name) AS tab
WHERE  id=1
GROUP  BY `date` 

由于它不相关,因此应该具有相当不错的性能。

编辑

受环境的启发,我修改了我的查询,事实上还有一个需要改进的地方。

SELECT a.`date` AS adt,
       Sum(CASE
             WHEN b.`date` IS NULL THEN 1
             ELSE 0
           end) AS unq
FROM   some_table AS a
       LEFT JOIN some_table AS b
              ON ( a.id = b.id
                   AND a.name = b.name
                   AND a.`date` > b.`date` )
WHERE  a.id = 1
GROUP  BY a.`date`,
          a.id;  

如有疑问,您可以检查sqlfiddle并最终与其他建议的解决方案进行比较。

于 2012-09-18T09:34:18.990 回答