2015-04-03 70 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

相關問題