Mysql
 sql >> Datenbank >  >> RDS >> Mysql

mysql zählt zeilen mit loop

Sie müssen damit arbeiten, ob die Garantie noch gültig oder abgelaufen ist, und das Garantiedatum, also müssen Sie zuerst eine Tabelle erstellen, die dies widerspiegelt:

select   product
       , IF( warranty >= NOW(), 1, 0 ) as valid
       , IF( warranty < NOW(), 1, 0 ) as expired
       , warranty as last
from     (
           select   product
                ,   ADDDATE( purchased, INTERVAL 5 YEAR ) as warranty
           from     productWarranty
         ) w
group by product
;

Das würde Ihnen so etwas bringen:

+---------+-------+---------+---------------------+
| product | valid | expired | warranty            |
+---------+-------+---------+---------------------+
| Hammer  |     1 |       0 | 2017-01-01 00:00:00 |
| Nipper  |     1 |       0 | 2017-01-01 00:00:00 |
| Nipper  |     1 |       0 | 2017-01-01 00:00:00 |
| Nipper  |     1 |       0 | 2017-01-01 00:00:00 |
| Saw     |     1 |       0 | 2017-01-01 00:00:00 |
| Saw     |     0 |       1 | 2011-01-01 00:00:00 |
| Saw     |     1 |       0 | 2017-01-01 00:00:00 |
| Saw     |     1 |       0 | 2017-01-01 00:00:00 |
+---------+-------+---------+---------------------+

Verwenden Sie dann Aggregatfunktionen, um die gesuchten Informationen zu filtern und zusammenzufassen:

select   product
       , SUM( IF( warranty >= NOW(), 1, 0 ) ) as valid
       , SUM( IF( warranty < NOW(), 1, 0 ) ) as expired
       , MAX( warranty ) as last
from     (
           select   product
                  , adddate( purchased, interval 5 year ) as warranty
           from productWarranty
         ) w
group by product
;
+---------+-------+---------+---------------------+
| product | valid | expired | last                |
+---------+-------+---------+---------------------+
| Hammer  |     1 |       0 | 2017-01-01 00:00:00 |
| Nipper  |     3 |       0 | 2017-01-01 00:00:00 |
| Saw     |     3 |       1 | 2017-01-01 00:00:00 |
+---------+-------+---------+---------------------+