从mysql中的表中获取所有日期数据的计数总和

时间:2014-04-01 03:33:29

标签: mysql datetime select

Table: call_details
-------------------
userId

phoneNumber

callDate

callType

callDuration

现在我想要一个查询来根据日期和类型获取详细信息。

就像,我想要日期的callType总数的SUM。

28-03-2014 - there are total 1 missed call, 2 incoming call and 5 outgoing calls

29-03-2014 - there are total 0 missed call, 5 incoming call and 10 outgoing calls.

30-03-2012 - there are total 5 missed call, 10 incoming call and 35 outgoing calls.

我的查询 -

SELECT `callType`, `callDate`, count(`callType`) as type FROM `tbl_call_details` GROUP BY `callType` ORDER BY `callDate` ASC


callType    callDate    count

OUTGOING    2014-03-28  52
INCOMING    2014-03-30  11
MISSED  2014-03-31  1

结果是错误的,因为它没有给我单独的结果日期。它只是挑选日期进入数据库并显示所有内容。我希望所有类型的日期明智地分开日期结果。

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合执行此操作:

SELECT date(`callDate`),
       sum(calltype = 'MISSED') as NumMissed,
       sum(callType = 'INCOMING') as NumIncoming,
       sum(callType = 'OUTGOING') as NumOutgoing
FROM `tbl_call_details`
GROUP BY date(`callDate`)
ORDER BY date(`callDate`) ASC;

这会将值放在列中。如果你想把它们作为一个字符串,你可以这样做:

SELECT date(`callDate`),
        concat('there are ', sum(calltype = 'MISSED'), ' missed call, '
               sum(callType = 'INCOMING'), ' incoming call and '
               sum(callType = 'OUTGOING'), ' outgoing calls'
              )
FROM `tbl_call_details`
GROUP BY date(`callDate`)
ORDER BY date(`callDate`) ASC;

答案 1 :(得分:0)

你也想通过callDate分组:

SELECT `callType`, `callDate`, count(`callType`) as type FROM `tbl_call_details` GROUP BY `callDate`, `callType` ORDER BY `callDate` ASC