sql >> Database teknologi >  >> RDS >> Mysql

mysql tæller rækker med loop

Det du skal arbejde med er, om garantien stadig er gyldig eller udløbet og garantidatoen, så du skal først bygge en tabel, der afspejler det:

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
;
 

Det ville give dig sådan noget:

+---------+-------+---------+---------------------+ | 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 | +---------+-------+---------+---------------------+

Brug derefter aggregerede funktioner til at filtrere og opsummere de oplysninger, du leder efter:

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 | +---------+-------+---------+---------------------+

  1. Sådan installeres PostgreSQL på macOS

  2. Tjek om et objekt er en lagret procedure ved at bruge OBJECTPROPERTY() i SQL Server

  3. Få tidspunktet for en datetime ved hjælp af T-SQL?

  4. At SHA512-hash en adgangskode i MySQL-database af Python