sql >> Databasteknik >  >> RDS >> Mysql

Få rekord per månad men få även noll om inga rekord den månaden

SELECT  Months.m AS month, COUNT(Tests.receiveDate) AS total FROM 
(
    SELECT 1 as m 
    UNION SELECT 2 as m 
    UNION SELECT 3 as m 
    UNION SELECT 4 as m 
    UNION SELECT 5 as m 
    UNION SELECT 6 as m 
    UNION SELECT 7 as m 
    UNION SELECT 8 as m 
    UNION SELECT 9 as m 
    UNION SELECT 10 as m 
    UNION SELECT 11 as m 
    UNION SELECT 12 as m
) as Months
LEFT JOIN Tests  on Months.m = MONTH(Tests.receiveDate)  
GROUP BY
    Months.m

Om du vill ha ett specifikt år, prova detta.

SELECT  Months.m AS month, COUNT(Tests.receiveDate) AS total FROM 
(
    SELECT 1 as m 
    UNION SELECT 2 as m 
    UNION SELECT 3 as m 
    UNION SELECT 4 as m 
    UNION SELECT 5 as m 
    UNION SELECT 6 as m 
    UNION SELECT 7 as m 
    UNION SELECT 8 as m 
    UNION SELECT 9 as m 
    UNION SELECT 10 as m 
    UNION SELECT 11 as m 
    UNION SELECT 12 as m
) as Months
LEFT JOIN Tests on Months.m = MONTH(Tests.receiveDate)  
AND YEAR(Tests.receiveDate) = '2012'
GROUP BY Months.m


  1. Hur man normaliserar en SQL-databas

  2. Skillnaden mellan VARCHAR2(10 CHAR) och NVARCHAR2(10)

  3. FEL:kunde inte ange filen XX.csv:Okänt fel

  4. MySQL fel nr 121