2015-04-03 53 views
1

我有这样的一个表:计数过期未到期及行数为每个唯一ID

| id  | certificate|expires | 
|  1 |  123 |12-DEC-15 | 
|  1 |  123 |12-DEC-09 | 
|  1 |  123 |13-DEC-09 | 
|  2 |  456 |14-DEC-16 | 
|  2 |  456 |14-DEC-09 | 
|  2 |  789 |14-DEC-09 | 
|  2 |  789 |14-DEC-09 | 

我试图总结这些过期,未过期一样为每个用户证书的数量这个:

|id | expired | unexpired | 
|1 |2  |1   | 
|2 |3  |1   | 

我已经设法计算所有已过期的证书,但它只显示没有过期的行数。如何获取过期证书的数量?

SELECT 
     id, 
     COUNT(certificate) as numcerts, 
     expires 
    FROM 
    certificates 
    WHERE 
    expires > current_date() 
    GROUP BY id 
    having numcerts > 0 
    ORDER BY COUNT(*) DESC 
+0

你明确地过滤出来的'期满> CURRENT_DATE()' – zerkms 2015-04-03 10:45:01

+0

使用STR_TO_DATE使文本变成公关操作日期 – Mihai 2015-04-03 10:45:15

回答

3

如果这两个日期都存储在date数据类型,则下面的查询会给你的结果

select 
id, 
sum(case when expires < curdate() then 1 else 0 end) as expires, 
sum(case when expires > curdate() then 1 else 0 end) as unsepired 
from certificates group by id 

如果日期存储为varchar你在给定的例子有办法,那么你需要使用str_to_date功能

select 
id, 
sum(case when str_to_date(expire,'%d-%b-%y') < curdate() then 1 else 0 end) as expires, 
sum(case when str_to_date(expire,'%d-%b-%y') > curdate() then 1 else 0 end) as unsepired 
from certificates group by id 
+0

非常感谢。那个答案很完美。 – 2015-04-03 10:59:18