我现在有一个查询,显示我这次之间的所有通话,是否有办法将其格式化为在一个查询中显示“day(9-5)”和“night(5-12)”?
select dst, count(dst) as Day from cdr
WHERE lastapp='Queue'
AND Date(calldate) = '2012-03-23'
AND TIME(calldate) BETWEEN '08:00' AND '17:00'
GROUP BY dst;
+------+-----+
| dst | Day |
+------+-----+
| 1010 | 10 |
| 1011 | 21 |
| 1012 | 7 |
+------+-----+
我理想的是这样,所以我可以在PHP中使用数组获取它而无需进行2次查询。
+------+-----+-------+
| dst | Day | Night |
+------+-----+-------+
| 1010 | 10 | 20 |
| 1011 | 21 | 12 |
| 1012 | 7 | 4 |
+------+-----+-------+
答案 0 :(得分:0)
是;你可以这样写:
SELECT dst,
COUNT(IF(TIME(calldate) BETWEEN '08:00' AND '17:00', 1, NULL)) AS Day,
COUNT(IF(TIME(calldate) > '17:00', 1, NULL)) AS Night
FROM cdr
WHERE lastapp = 'Queue'
AND DATE(calldate) = '2012-03-23'
GROUP
BY dst
;
(COUNT(...)
计算...
非空的行数。IF(boolean, value_if_true, value_if_false)
执行听起来的行为 - 请参阅http://dev.mysql.com/doc/refman/5.6/en/control-flow-functions.html#function_if - 尽管我应该提到它是特定于MySQL的函数。如果您没有专门将您的问题标记为MySQL,我建议使用CASE WHEN boolean THEN value_if_true ELSE value_if_false END
,因为这是大多数或所有DMBS支持的标准语法。)