我有两个已连接的表格,“报告”和“访问次数”以及类似的查询:
SELECT reports.rep_dated,
(SELECT COUNT(*) FROM visits
WHERE visits.vis_report = reports.rep_id) AS vis_count
FROM reports
HAVING vis_count > 0
ORDER BY rep_dated
返回以下数据:
+------------+-----------+
| rep_dated | vis_count |
+------------+-----------+
| 2013-11-03 | 3 |
| 2013-11-07 | 4 |
| 2013-11-28 | 2 |
| 2013-11-28 | 3 |
+------------+-----------+
到目前为止一直这么好(你看到rep_dated可以重复,因为它不是主键:那是因为第一个“2013-11-28”指的是完成AM的访问,第二个指的是完成的访问PM)< / p>
现在我想在同一天的时间内完成访问(也就是访问AM + PM的SUM次数),然后返回:
+------------+-----------+
| rep_dated | vis_count |
+------------+-----------+
| 2013-11-03 | 3 |
| 2013-11-07 | 4 |
| 2013-11-28 | 5 |
+------------+-----------+
而且,正如你已经想象的那样,这就是我被卡住的地方......
GROUP BY reports.rep_dated
不起作用......我怎么能得到那套呢?
在此先感谢您的帮助!
答案 0 :(得分:0)
试试这个:
SELECT reports.rep_dated, SUM(visits.vis_report) AS vis_count
FROM reports, visits
WHERE visits.vis_report = reports.rep_id
GROUP BY reports.rep_dated
HAVING vis_count > 0
ORDER BY rep_dated
答案 1 :(得分:0)
在Mysql中使用Group By或ORDER时,您不需要提及表名。 试试
GROUP BY rep_dated
答案 2 :(得分:0)
试试这个:
SELECT reports.rep_dated,
COUNT(*) AS vis_count
FROM VISITS
JOIN reports ON visits.vis_report = reports.rep_id
GROUP BY reports.rep_dated
ORDER BY reports.rep_dated