Question : SQL COUNT statement using JOIN between TBLS

SQL 1:

Below is the example data in two tables, one called statistic and one called address. I need to write an SQL count statement that gives me the results below these two tables which is basically top visited cities in order of popularity.

table called 'statistic'

statisticid | addressid | listingid
--------------------------------------
    1       |       1     |      9
--------------------------------------
    2       |       3      |      2
--------------------------------------
    3       |       1      |      10
--------------------------------------
    4       |       3      |      4
--------------------------------------
    5       |       2      |      6
--------------------------------------
    6       |       1      |      1
--------------------------------------
    7       |       1      |      7
--------------------------------------

table called 'address'

addressid | city |
-------------------------
      1      |      LONDON
-------------------------
      2      |      GLASGOW
-------------------------
      3      |      BELFAST
-------------------------

DESIRED RESULTS SQL.1

location | hits      |
-------------------------
LONDON   |   4
-------------------------
BELFAST   |   2
-------------------------
GLASGOW   |  1
-------------------------

SQL 2:

Then it gets a little trickier, using the statistic table above again and the table below called listing, I need to find the most visited category.

table called 'listing'

listingid  |  category
-------------------------
1    |    beer
-------------------------
2    |    beer
-------------------------
3    |    cider
-------------------------
4    |    spirits
-------------------------
5    |    water
-------------------------
6    |    juice
-------------------------
7    |    wine
-------------------------
8    |    coffee
-------------------------
9    |    beer
-------------------------
10    |    spirits
-------------------------

DESIRED RESULTS SQL.2

category    |      hits
-------------------------
beer    |      3
-------------------------
spirits    |      2
-------------------------
juice    |      1
-------------------------
wine    |      1
-------------------------

It's all probably very simple but I'm new to count statements in SQL. Please note that I'm running SQL Server 2005 so it must be SQL that is compatible with this.

Thanks!

Answer : SQL COUNT statement using JOIN between TBLS

OK, same way as for the first example:


SELECT l.category, COUNT(*) AS Hits
FROM listing l INNER JOIN
      statistic s ON l.avertid = s.advertid
GROUP BY l.category
ORDER BY COUNT(*) DESC


To include the ones with no hits...

SELECT l.category, COUNT(*) AS Hits
FROM listing l LEFT JOIN
      statistic s ON l.avertid = s.advertid
GROUP BY l.category
ORDER BY COUNT(*) DESC
Random Solutions  
 
programming4us programming4us