mysql> describe taps;
+------------+-----------+------+-----+-------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-----------+------+-----+-------------------+-------+
| tag | int(11) | NO | | NULL | |
| station | int(11) | NO | | NULL | |
| time_Stamp | timestamp | NO | | CURRENT_TIMESTAMP | |
+------------+-----------+------+-----+-------------------+-------+
3 rows in set (0.00 sec)
如何获得每个标记访问过的网站数量,并按最多访问次数排序 - 我们只计算一次访问每个网站,即使有多个访问次数?
随机数据:
mysql> select * from taps;
+-----+---------+---------------------+
| tag | station | time_Stamp |
+-----+---------+---------------------+
| 50 | 12 | 2016-05-10 20:02:41 |
| 33 | 7 | 2016-05-10 20:02:42 |
| 34 | 13 | 2016-05-10 20:02:42 |
| 31 | 3 | 2016-05-10 20:02:42 |
| 9 | 10 | 2016-05-10 20:02:42 |
| 2 | 11 | 2016-05-10 20:02:42 |
| 33 | 13 | 2016-05-10 20:02:42 |
| 46 | 12 | 2016-05-10 20:02:42 |
| 45 | 1 | 2016-05-10 20:02:42 |
| 34 | 7 | 2016-05-10 20:02:42 |
| 4 | 10 | 2016-05-10 20:08:18 |
| 17 | 5 | 2016-05-10 20:08:19 |
| 46 | 7 | 2016-05-10 20:08:19 |
| 16 | 5 | 2016-05-10 20:08:19 |
| 33 | 3 | 2016-05-10 20:08:19 |
| 31 | 4 | 2016-05-10 20:08:19 |
| 1 | 13 | 2016-05-10 20:08:19 |
| 35 | 2 | 2016-05-10 20:08:19 |
| 9 | 12 | 2016-05-10 20:08:19 |
| 26 | 7 | 2016-05-10 20:08:19 |
+-----+---------+---------------------+
20 rows in set (0.00 sec)
答案 0 :(得分:1)
假设我正确理解您的问题,您只需将count
与distinct
一起使用:
select tag, count(distinct station) cnt
from taps
group by tag
order by 2 desc
答案 1 :(得分:1)
使用COUNT
功能和GROUP BY
查找每个tag
的访问次数。
并使用ORDER BY
子句按访问次数的降序对结果进行排序。
<强>查询强>
SELECT tag, COUNT(DISTINCT station) AS `no of visits`
FROM taps
GROUP BY tag
ORDER BY COUNT(DISTINCT station) DESC;