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

hent data grupperet efter måned ved hjælp af mysql-interval

Prøv dette

SELECT d.y, d.m, p.cnt 
FROM 
    (SELECT a.y, b.m 
    FROM (SELECT 2015 AS Y UNION ALL SELECT 2014 AS Y) a
    CROSS JOIN (SELECT 1 AS m UNION ALL SELECT 2 AS m UNION ALL SELECT 3 AS m UNION ALL SELECT 4 AS m UNION ALL SELECT 5 AS m UNION ALL SELECT 6 AS m UNION ALL SELECT 7 AS m UNION ALL SELECT 8 AS m UNION ALL SELECT 9 AS m UNION ALL SELECT 10 AS m UNION ALL SELECT 11 AS m UNION ALL SELECT 12 AS m) b
    WHERE CONCAT(a.y, '-', b.m, '-01') BETWEEN CURDATE() - INTERVAL 13 MONTH AND CURDATE() - INTERVAL 1 MONTH
    ORDER BY 1, 2) d
    LEFT OUTER JOIN
    (SELECT YEAR(purchasedate) AS Y ,MONTH(purchasedate) AS m, COUNT(*) cnt FROM purchase WHERE productid=1001 AND purchasedate >= CURDATE() - INTERVAL 1 YEAR GROUP BY m, Y) p ON d.m=p.m AND d.y=p.y
ORDER BY 1 DESC, 2

Du gør ikke noget forkert, men MySQL kan ikke returnere rækker i måneder, som ikke findes i dit datasæt. For at løse dette problem skal du selv angive alle måneder (tabel d i denne forespørgsel) og LEFT JOIN dem med resultater fra dit datasæt




  1. mysql-php forespørger på en liste for at bygge en tabel

  2. Kopier i Postgresql:Absolut sti tolket som relativ sti

  3. Hvordan linker Wordpress indlæg til kategorier i sin database?

  4. Mysql Concat to kolonner, mens du søger med LIKE