http://topic.csdn.net/u/20071221/15/88c1036a-7c55-4ea2-94b8-c739c0c616f3.html大家帮忙看看上面的帖子谢谢

解决方案 »

  1.   

    参考。mysql> create table test1 (id int not null,f_date datetime not null);
    Query OK, 0 rows affected (0.00 sec)mysql> insert into test1 values (1,'2007/12/21 12:00'), (2,'2007/12/21 01:00'),(3,'2007/12/21 03:00');
    Query OK, 3 rows affected (0.00 sec)
    Records: 3  Duplicates: 0  Warnings: 0mysql> create temporary table test_hour 
        -> (id int not null);
    Query OK, 0 rows affected (0.01 sec)mysql> insert into test_hour values
        -> (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15),(16),(17),(18),(19),(20),(21),(22),(23),(0);
    Query OK, 24 rows affected (0.00 sec)
    Records: 24  Duplicates: 0  Warnings: 0mysql> create temporary table tmp select id, f_date,hour(f_date) h from test1;
    Query OK, 3 rows affected (0.01 sec)
    Records: 3  Duplicates: 0  Warnings: 0mysql> select count(b.id) cnt, sum(case when b.h is null then 0 else 1 end) h  from test_hour a left join tmp b on a.id = b.h group by a.id;
    +-----+------+
    | cnt | h    |
    +-----+------+
    |   0 |    0 | 
    |   1 |    1 | 
    |   0 |    0 | 
    |   1 |    1 | 
    |   0 |    0 | 
    |   0 |    0 | 
    |   0 |    0 | 
    |   0 |    0 | 
    |   0 |    0 | 
    |   0 |    0 | 
    |   0 |    0 | 
    |   0 |    0 | 
    |   1 |    1 | 
    |   0 |    0 | 
    |   0 |    0 | 
    |   0 |    0 | 
    |   0 |    0 | 
    |   0 |    0 | 
    |   0 |    0 | 
    |   0 |    0 | 
    |   0 |    0 | 
    |   0 |    0 | 
    |   0 |    0 | 
    |   0 |    0 | 
    +-----+------+
    24 rows in set (0.00 sec)