This Query has become my favorite query to use. It seems like every time I turn around I need to count how many times that a number or word appears in ONE column of a database. For instance, I have a voting system which allows you to vote either, 1, 2, 3, 4, or 5. I then insert that into one column named “votOne” in the table tblRateSeason3. Now for example, to show the results of how many people voted 5, I need to count all the 5’s in the database. This can be done using the sweet CASE function within a SUM function in SQL. Here is how it looks:
-
SELECT votOne,
-
sum(case when votOne = 1 then 1 else 0 end) AS 'One',
-
sum(case when votOne = 2 then 1 else 0 end) AS 'Two',
-
sum(case when votOne = 3 then 1 else 0 end) AS 'Three',
-
sum(case when votOne = 4 then 1 else 0 end) AS 'Four',
-
sum(case when votOne = 5 then 1 else 0 end) AS 'Five'
-
FROM rate_season3