我希望使用MySQL获得一年的销售额

时间:2012-11-07 10:26:12

标签: mysql sql

我希望得到以下年度的结果

month | sales
jan     0.00
feb     4.00
mar     0.00
apr     45.00
.
.
.
.
dec    0.00

我拥有的表是“sales”,它有salse_value,sales_date为列。

问题是如何在MYSQL中使用case语句获得上述结果

3 个答案:

答案 0 :(得分:1)

SELECT MONTHNAME(date_column), SUM(sales) sales
FROM TableName
GROUP BY MONTHNAME(date_column);

答案 1 :(得分:1)

您需要生成所有月份名称并将其与您的表格名称一起加入,因此没有记录的月份将占总销售额的零值

SELECT  a.MonthName, COALESCE(SUM(b.sales_value), 0) totalSales
FROM    
        (
            SELECT 'Jan' AS monthName, 1 monthOrder
            UNION
            SELECT 'Feb' AS monthName, 2 monthOrder
            UNION
            SELECT 'Mar' AS monthName, 3 monthOrder
            UNION
            SELECT 'Apr' AS monthName, 4 monthOrder
            UNION
            SELECT 'May' AS monthName, 5 monthOrder
            UNION
            SELECT 'Jun' AS monthName, 6 monthOrder
            UNION
            SELECT 'Jul' AS monthName, 7 monthOrder
            UNION
            SELECT 'Aug' AS monthName, 8 monthOrder
            UNION
            SELECT 'Sep' AS monthName, 9 monthOrder
            UNION
            SELECT 'Oct' AS monthName, 10 monthOrder
            UNION
            SELECT 'Nov' AS monthName, 11 monthOrder
            UNION
            SELECT 'Dec' AS monthName, 12 monthOrder
        )   a LEFT JOIN sales b
                ON a.monthName = b.monthName
GROUP BY a.monthName
ORDER BY a.MonthOrder ASC

答案 2 :(得分:0)

如果您想获得月份的缩写名称,可以尝试

SELECT DATE_FORMAT(sales_date, '%b') AS month, SUM(sales_value)
FROM sales
GROUP BY month;

如果没有特定月份的记录,则该月份不会包含任何行。