计算一年中每个月的状态为“已关闭”且状态为“未关闭”的行

时间:2016-11-03 05:04:49

标签: mysql

这是表,我需要获取状态cloesd的行数和一年中每个月未关闭的状态。提前谢谢。

表格图片

enter image description here

4 个答案:

答案 0 :(得分:0)

select count(*) from table1
where status in ('closed,unclosed')
group by status,month(call_time)   

答案 1 :(得分:0)

试试这个:

SELECT COUNT(*) FROM <table name> WHERE status="closed"; 


SELECT COUNT(*) FROM <table name> WHERE status="unclosed";

答案 2 :(得分:0)

使用YEAR和月份部分使用MONTH函数和表中的status列从日期中获取部分,并将其用作子集,然后使用CASE表达式按年份和月份计算ClosedUnclosed状态组。

<强>查询

SELECT t.`YEAR`, t.`MONTH`,
SUM(CASE t.`status` WHEN 'Closed' THEN 1 ELSE 0 END) AS `Closed`,
SUM(CASE t.`status` WHEN 'Unclosed' THEN 1 ELSE 0 END) AS `UnClosed`
FROM(
    SELECT YEAR(`call_time`) AS `YEAR`,
    MONTH(`call_time`) AS `MONTH`,
    `status`
    FROM `your_table_name`
)t
GROUP BY t.`YEAR`, t.`MONTH`;

SQL Fiddle demo

答案 3 :(得分:0)

您可以尝试以下查询。

SELECT *
FROM 
(
    (
        SELECT MONTH(mt1.calltime) AS MONTH, YEAR(mt1.`calltime`) AS YEAR, COUNT(mt1.`status`) AS closed, 0 AS unclosed
        FROM myTable mt1
        WHERE mt1.`status`='closed'
    )
    UNION ALL
    (
        SELECT MONTH(mt2.calltime) AS MONTH, YEAR(mt2.`calltime`) AS YEAR, 0 AS closed, COUNT(mt2.`status`) AS unclosed
        FROM myTable mt2
        WHERE mt2.`status`='unclosed'
    )
) AS tablea
GROUP BY tablea.month

myTable替换为您的表名。

MONTH将从指定日期提取一年中的一个月,而YEAR将提供一年。

<强> SQL FIDDLE