sql >> Database >  >> RDS >> Mysql

MySQL WEEK() :Krijg alle weken in het datumbereik (met/zonder records)

Ervan uitgaande dat u een tabel met gehele getallen hebt (genaamd `numbers` hieronder):

   SELECT COALESCE(n, 0) AS num_complaints, CONCAT('Week ', i) AS `week`
     FROM (SELECT i
             FROM numbers
            WHERE i BETWEEN (SELECT WEEK(MIN(complaintRaisedDate)) FROM events LIMIT 1)
                            AND
                            (SELECT WEEK(MAX(complaintRaisedDate)) FROM events LIMIT 1))
          week_ranges
LEFT JOIN (  SELECT count(id) AS n, WEEK(complaintRaisedDate) AS weeknum
               FROM events
              WHERE categoryId=1
           GROUP BY weeknum) weekly_tallies
       ON week_ranges.i = weekly_tallies.weeknum
 ORDER BY `week` ASC;

SQL-viool



  1. Eerste element in database SQL Query verwijderen

  2. Hoe citeer je strings in Postgres

  3. Die verdomd grote objecten

  4. Tijdelijke tabellen maken in MySQL Stored Procedure