Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

mysql menghitung baris dengan loop

Yang perlu Anda tangani adalah apakah garansi masih berlaku atau kedaluwarsa dan tanggal garansi, jadi Anda harus terlebih dahulu membuat tabel yang mencerminkan bahwa:

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
;

Itu akan memberi Anda sesuatu seperti itu:

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

Kemudian gunakan fungsi agregat untuk memfilter dan meringkas informasi yang Anda cari:

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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Bagaimana cara menghasilkan bacaan phantom?

  2. MySQL INNER GABUNG Alias

  3. Hasil basi kronis menggunakan MySQLdb dengan Python

  4. Mengakses baris yang terakhir dibuat di PHP/MySQL

  5. Jumlahkan total dua kueri