我正在尝试创建一个检查客户端表的查询,并返回具有最近30天,365天和所有时间的特定值的用户数。
所有时间都很简单:
$stmt = $conn->prepare("SELECT count(id) AS count FROM clients WHERE referred = :refid");
$stmt->bindParam(':refid', $refid);
$stmt->execute();
$totalreferrals = $stmt->fetchAll();
表:
id | signup | reffered |
----------------------------
2 | 2012-08-24 | 14 |
----------------------------
3 | 2011-10-13 | 14 |
我不确定是否可以使用UNION组合查询,或者我是否应该只进行三个不同的查询。有什么帮助吗?
答案 0 :(得分:6)
我认为你想在列中而不是在行中,如果是这样的话,那么
SELECT COUNT(CASE WHEN DATEDIFF(CURDATE(),signup) <= 30 THEN id
ELSE NULL
END) AS Last30days ,
COUNT(CASE WHEN DATEDIFF(CURDATE(), signup) <= 365 THEN id
ELSE NULL
END) AS Last365Days ,
COUNT(*) AS Alltime
FROM Table1
WHERE reffered = 14
SQLFiddle http://sqlfiddle.com/#!2/6e6ce/2
答案 1 :(得分:0)
也许这可以解决问题:
SELECT count(id) AS count FROM clients WHERE referred = :refid AND BETWEEN ADDDATE(NOW(), INTERVAL -1 MONTH) AND NOW();
SELECT count(id) AS count FROM clients WHERE referred = :refid AND BETWEEN ADDDATE(NOW(), INTERVAL -1 YEAR) AND NOW();