从桌子中选择独特的

时间:2012-09-18 08:12:39

标签: php mysql

大家好我有一个mysql db表如下

      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的唯一名称。 例如。 为16 sep。 uniques = 2,因为在此表中16个sep之前不会出现A,E。 为17 sep。 uniques = 1,因为D在此表中17 sep之前没有出现,A已经在16 sep上发生。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 |
+------------+---------+

答案 2 :(得分:-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,并最终与其他建议的解决方案进行比较。