假设我有一个名为“productClick”的表,如下所示:
----id------click-------------ctime----------
| 1 | 5 | 2015-12-26 00:01:12 |
---------------------------------------------
| 2 | 2 | 2015-12-27 00:01:12 |
---------------------------------------------
| 3 | 7 | 2015-12-28 00:01:12 |
---------------------------------------------
| 4 | 1 | 2015-12-28 00:01:12 |
---------------------------------------------
我希望获得产品总数,今天添加的产品总数以及总点击次数之和。
我有三个单独的查询:
SELECT COUNT(*) as totalProduct FROM productClick
SELECT COUNT(*) as todayTotalProductAdded FROM productClick WHERE DATE(`ctime`) = CURDATE()
SELECT sum(click) as totalClick FROM productClick
工作正常。但我想将这三个单独的查询合并为一个查询。怎么做到这一点?
更新
问题已更新。抱歉我的错。谢谢 @Gordon Linoff
答案 0 :(得分:3)
您可以使用条件聚合:
SELECT COUNT(*) as totalProduct,
SUM(click) as totalClick,
SUM(DATE(ctime) = CURDATE()) as todayClick
FROM productClick
todayClick
是:
SUM(CASE WHEN DATE(ctime) = CURDATE() THEN 1 ELSE 0 END) as todayClick
如果您想要多行,请或UNION ALL
:
SELECT 'totalProduct' AS counter_name, COUNT(*) AS counter_value FROM productClick
UNION ALL
SELECT 'todayClick', COUNT(*) FROM productClick WHERE DATE(ctime) = CURDATE()
UNION ALL
SELECT 'totalClick', SUM(click) FROM productClick
修改强>
今天添加的产品总数和总点击次数之和。
SELECT COUNT(*) as totalProduct,
SUM(click) as totalClick,
SUM(CASE WHEN DATE(ctime) = CURDATE() THEN click ELSE 0 END) as todayClick
FROM productClick