简体   繁体   中英

SQL query for top 3 results

I've set of pages and each page has PageID and will record unique visitors information IP , Country , Browser , System and Date of visit

Here is sample of the database table

-------------------------------------------------------------------
| PageID |     IP     | Country |  Browser | System  |   Date     | 
-------------------------------------------------------------------
|    1   | 00-00-00-1 |   UK    |  Chrome  |   Win7  | 2016-05-22 |
-------------------------------------------------------------------
|    6   | 00-00-00-2 |  France | Firefox  |   Win8  | 2016-05-25 |
-------------------------------------------------------------------
|    1   | 00-00-00-3 |   USA   | Firefox  |  WinXP  | 2016-05-26 |
-------------------------------------------------------------------
|    8   | 00-00-00-4 |  Spain  |   Opera  | Android | 2016-05-28 |
-------------------------------------------------------------------
|    1   | 00-00-00-5 |    UK   |  Chrome  |  Win10  | 2016-06-01 |
-------------------------------------------------------------------
|    8   | 00-00-00-6 |  Italy  |  Safari  |Kardishan| 2016-06-02 |
-------------------------------------------------------------------
|    5   | 00-00-00-7 |   USA   | Unknown  | Android | 2016-06-02 |
-------------------------------------------------------------------
|    3   | 00-00-00-8 |    UK   |  Firefox |   Win7  | 2016-06-02 |
-------------------------------------------------------------------

My questions

1) How to make query to get top 3 countries where visitors comes from ? from the above sample the results should be :-

UK        3
USA       2
France    1

2) How to same query to get top 3 countries where visitors comes from where PageID = 1 from the above sample the results should be :-

UK    2
USA   1

~ that would helps me a lot to understand how statics can be generated, thanks

This would give you the top 3 countries overall:

SELECT Country, COUNT(*)
FROM mytable
GROUP BY Country 
ORDER BY COUNT(*) DESC LIMIT 3

To get the top 3 for a specific PageID just add a WHERE PageID = 1 clause.

SELECT Country, COUNT(*) AS Visits
FROM <your_table_name>
GROUP BY Country
ORDER BY Visits;

This will get all countries along with the number of visits from the desired country in a descending order. Depending on your type of usage you may also add LIMIT 3 to only get the top 3.

To only get visits to page with ID 1 you can use this similar query:

SELECT Country, COUNT(*) AS Visits
FROM <your_table_name>
WHERE pageID=1
GROUP BY Country
ORDER BY Visits;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM