mysql counting rows with loop

前端 未结 3 965
旧巷少年郎
旧巷少年郎 2021-01-25 07:31

I have the following table:

+-------------+--------------+ 
| product     | purchased    |
+-------------+--------------+ 
| Hammer      |   |
|         


        
3条回答
  •  滥情空心
    2021-01-25 07:57

    What you need to work with is whether the warranty is still valid or expired and the warranty date, so you first need to build a table that reflects that:

    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
    ;
    

    That would get you something like that:

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

    Then use aggregate functions to filter and sum up the information you're looking for:

    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
                      , affffdate( 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 |
    +---------+-------+---------+---------------------+
    

提交回复
热议问题