1

我有一张表:apns_devices有列:estado, modified, pid, etc. 我想根据上次修改时间(即上周、上个月、昨天、今天和总数)获得一些统计信息。现在我正在为每个时期做一个查询(嵌套),例如:

SELECT t1.estado, t1.siempre, t2.hoy
FROM 
(SELECT *, COUNT(pid) as siempre FROM `apns_devices` GROUP BY estado) as t1
INNER JOIN 
(SELECT *, COUNT(pid) as hoy   FROM `apns_devices` WHERE DATE (modified) = CURRENT_DATE GROUP BY estado) as t2 
ON t1.estado = t2.estado

这是今天的总和

为了加快脚本速度;¿ 我怎样才能在一个查询中做到这一点?

4

2 回答 2

2
SELECT
  estado,
  COUNT(*) siempre,
  COUNT(CASE WHEN DATE(modified) = CURDATE() THEN 1 END) AS ModifiedToday,
  COUNT(CASE WHEN DATEDIFF(CURDATE(), modified) = 1 THEN 1 END) AS ModifiedYesterday,
  COUNT(CASE WHEN DATEDIFF(CURDATE(), modified) BETWEEN 2 AND 7 THEN 1 END) AS ModifiedLastWeek,
  COUNT(CASE WHEN DATEDIFF(CURDATE(), modified) BETWEEN 8 AND 30 THEN 1 END) AS ModifiedYesterMonth
FROM
  apns_devices
GROUP BY
  estado

在此处查看小提琴。

于 2013-03-11T21:59:37.927 回答
1

试试这个查询

    SELECT distinct estado,  
(SELECT COUNT(pid) as hoy   FROM `apns_devices` WHERE estado = a.estado and DATE (modified) = CURRENT_DATE) AS ModifiedToday, 
(SELECT COUNT(pid) as hoy   FROM `apns_devices` WHERE estado = a.estado and CURRENT_DATE - DATE (modified) = 1) AS ModifiedYesterday, 
(SELECT COUNT(pid) as hoy   FROM `apns_devices` WHERE estado = a.estado and CURRENT_DATE - DATE (modified) BETWEEN 2 AND 8) AS ModifiedLastWeek, 
(SELECT COUNT(pid) as hoy   FROM `apns_devices` WHERE estado = a.estado and CURRENT_DATE - DATE (modified) BETWEEN 9 AND 30) AS ModifiedLastMonth 
FROM apns_devices a
于 2013-03-11T21:46:21.750 回答