MySql查询仅从范围获取周数据的最后一天

时间:2013-12-20 06:44:30

标签: mysql

我正在尝试在图表中显示“Test_Report”表的每周报告。 该表包含数千条记录和数十列。 每天都是工作日。给出了仅包含所需列的简化表。

Work_Week  Process    Status
--------- ----------  -------
6.2       Process 1    pass
6.2       Process 2    fail
6.2       Process 3    pass
6.2       Process 4    pass
6.2       Process 5    fail
9.1       Process 1    pass
9.1       Process 2    fail
9.1       Process 3    pass
9.1       Process 4    pass
9.1       Process 5    fail
9.2       Process 1    pass
9.2       Process 2    pass
9.2       Process 3    pass
9.2       Process 4    fail
9.2       Process 5    fail
9.4       Process 1    pass
9.4       Process 2    pass
9.4       Process 3    pass
9.4       Process 4    fail
9.4       Process 5    fail

我使用以下查询来获取状态的计数

SELECT Work_Week,
    COUNT(*) AS total,
    SUM(CASE WHEN STATUS = 'fail' THEN 1 ELSE 0 END) FailCount,
    SUM(CASE WHEN STATUS = 'pass' THEN 1 ELSE 0 END) PassCount
FROM Test_Report
GROUP BY Work_Week

我得到下表。这个数据很好。

Work_Week   total  FailCount  PassCount
---------  ------  ---------  ---------
     6.2     150          1        149
     9.1       1          0          1
     9.2       1          1          0
     9.4     268         59        208

现在我想要的是特定工作周的最后一天。即,只有上表中6.2和9.4的记录,因为该数据代表整周的结果。而且我期待像这样的东西

 Work_Week  total FailCount PassCount
--------   -------- -------- ---------
  6        150        1        149
  9        268        59       208

仅此结果将用于创建图表。 任何人都可以建议MySql查询这样做。 非常感谢任何帮助。 谢谢!

1 个答案:

答案 0 :(得分:2)

SELECT week,
       COUNT(*) AS total,
       SUM(CASE WHEN STATUS = 'fail' THEN 1 ELSE 0 END) AS FailCount,
       SUM(CASE WHEN STATUS = 'pass' THEN 1 ELSE 0 END) AS PassCount
FROM Test_Report
JOIN (SELECT SUBSTRING_INDEX(work_week, '.', 1) AS week, 
             MAX(substring_index(work_week, '.', -1)) AS last_day
      FROM Test_Report
      GROUP BY week) AS last_days
ON Work_week = CONCAT(week, '.', last_day)
GROUP BY week