单个mySQL查询中的多个select语句,其中group by子句共同

时间:2017-09-20 11:01:20

标签: mysql sql pivot

我正在尝试获得此输出。这是按日期分组与每天的错误代码计数。

select * FROM  
(select DATE(DATE_Record) AS Todays_Date from Sale_1 where (DATE_Record BETWEEN '2017-09-14 00:00:00' AND '2017-09-20 23:59:59') group by DAY(DATE_Record)) as DATE_1,
(select count(RESPONSECODE) AS 521_ERROR from Sale_1 where ERRORCODE='521' AND (DATE_Record BETWEEN '2017-09-14 00:00:00' AND '2017-09-14 23:59:59')) as 521_ERROR,
(select count(RESPONSECODE) AS 527_ERROR from Sale_1 where ERRORCODE='527' and (DATE_Record BETWEEN '2017-09-14 00:00:00' AND '2017-09-14 23:59:59')) as 527_ERROR;

但是对于这个查询,我只将日期分组为14,15,16,但错误代码的数量从9月14日到20日整数计算,并在每个日期旁边打印相同的数据。

我希望将日期作为第14组,其中错误代码的数量为14,紧接着是14,然后是15,错误代码的数量为15,接下来的15就像那样

请帮忙解决这个问题。

LSApplicationQueriesSchemes

2 个答案:

答案 0 :(得分:2)

不需要这些复杂的相关子查询。使用CASE表达式与GROUP BY日期一样简单:

SELECT
 DATE(Date_Record),
 SUM(CASE WHEN ERRORCODE = '521' THEN 1 ELSE 0 END )AS 521_ERROR,
 SUM(CASE WHEN ERRORCODE = '527' THEN 1 ELSE 0 END )AS 527_ERROR
FROM Table
WHERE DATE_Record BETWEEN '2017-09-14 00:00:00' AND '2017-09-20 23:59:59'
GROUP BY DATE(Date_Record);

或者你可以按照 @MKhalidJunaid 的建议缩短时间:

SELECT
 DATE(Date_Record),
 SUM(ERRORCODE = '521') AS 521_ERROR,
 SUM(ERRORCODE = '521') AS 527_ERROR
FROM Table
WHERE DATE_Record BETWEEN '2017-09-14 00:00:00' AND '2017-09-20 23:59:59'
GROUP BY DATE(Date_Record);

答案 1 :(得分:1)

您可以通过以下查询来完成。

select DATE(DATE_Record) AS "Todays_Date", sum(if(ERRORCODE=521,1,0)) as 521_ERROR, sum(if(ERRORCODE=527,1,0)) as 527_ERROR
FROM  Sale_1 
where (DATE_Record BETWEEN '2017-09-14 00:00:00' AND '2017-09-20 23:59:59') 
group by date(DATE_Record))