在MySql中按时间对COUNT进行分组

时间:2015-08-17 15:00:46

标签: mysql sql

我有一个简单的查询,它给了我应用程序类型的数量;它看起来像这样:

SELECT Application_Type, COUNT(*) FROM Loan_Applications GROUP BY Application_Type;

它返回如下内容:

Home 3
Car  21
Commercial 16

数据库中有一个名为 Submission_Date 的字段(日期类型为

如何按周查询和分解这些数据?

Type This week   Last week  2 weeks ago
Home    1            1          1
Car     9            6          6 
Commercial 10        0          3

3 个答案:

答案 0 :(得分:1)

您可以进行SUMIF类型的计算。以下内容总结了提交日期在上周内的行数。

SUM(CASE WHEN submission_date >= CURDATE() - 7 THEN 1 ELSE 0 END)

然后,您可以针对不同的范围重复此操作,以获得您想要的任何“乐队”。

答案 1 :(得分:1)

您可以尝试以下内容:

SELECT
    Application_Type,
    SUM(IF(Submission_Date BETWEEN CURRENT_DATE AND CURRENT_DATE - INTERVAL 1 WEEK, 1, 0)) AS 'This week',
    SUM(IF(Submission_Date BETWEEN CURRENT_DATE- INTERVAL 1 WEEK AND CURRENT_DATE - INTERVAL 2 WEEK, 1, 0)) AS 'Last week',
    SUM(IF(Submission_Date BETWEEN CURRENT_DATE- INTERVAL 2 WEEK AND CURRENT_DATE - INTERVAL 3 WEEK, 1, 0)) AS '2 weeks ago',
FROM Loan_Applications
GROUP BY Application_Type
;

或者:

SET @date1w  = CURRENT_DATE - INTERVAL 1 WEEK;
SET @date2w  = CURRENT_DATE - INTERVAL 2 WEEK;
SET @date3w  = CURRENT_DATE - INTERVAL 3 WEEK;
SELECT
    Application_Type,
    SUM(IF(Submission_Date BETWEEN CURRENT_DATE AND @date1w, 1, 0)) AS 'This week',
    SUM(IF(Submission_Date BETWEEN @date1w AND @date2w, 1, 0)) AS 'Last week',
    SUM(IF(Submission_Date BETWEEN @date2w AND @date3w, 1, 0)) AS '2 weeks ago',
FROM Loan_Applications
GROUP BY Application_Type
;

答案 2 :(得分:1)

尝试

SELECT 
Application_Type,
SUM(WEEKOFYEAR(Submission_Date) = WEEKOFYEAR(NOW())) AS `This week`,
SUM(WEEKOFYEAR(Submission_Date) = WEEKOFYEAR(DATE_ADD(NOW(),INTERVAL -1 WEEK))) AS `Last week`,
SUM(WEEKOFYEAR(Submission_Date) = WEEKOFYEAR(DATE_ADD(NOW(),INTERVAL -2 WEEK))) AS `2 weeks ago`
FROM Loan_Applications GROUP BY Application_Type;
;

它基于以下事实:group by中布尔表达式的SUM将计算表达式为true时的情况