我有一张这样的表:
| 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 :(得分: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