WeCodeThings Library
Library of code bits
Glossary    Contact Us
Need a web designer? visit WeCodeThings.Com for more details
Search  
   
Browse by Category


WeCodeThings Library .: SQL .: SQL Count Number of Times a Word or Number Appears in ONE Field or Column



SQL Count Number of Times a Word or Number Appears in ONE Field or Column

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:

 

  1. SELECT votOne, 
  2.                 sum(case when votOne = 1 then 1 else 0 end) AS 'One',
  3.                 sum(case when votOne = 2 then 1 else 0 end) AS 'Two',
  4.                 sum(case when votOne = 3 then 1 else 0 end) AS 'Three',
  5.                 sum(case when votOne = 4 then 1 else 0 end) AS 'Four',
  6.                 sum(case when votOne = 5 then 1 else 0 end) AS 'Five'
  7. FROM rate_season3


How helpful was this article to you?

Related Articles

article Change Font | Text color based on winning number or percentage using cfif ColdFusion
I just wanted to change the font or text...

(No rating)  4-19-2009    Views: 876   
article mySQL SQL Select the last 50 rows inserted into the database by using LIMIT
In mySQL you can show a specific number of...

(No rating)  8-3-2009    Views: 686   
article ColdFusion Initcap Capitalize the first letter of each word
If you've ever used Oracle, the Initcap...

  12-1-2009    Views: 1314   

User Comments

Add Comment
No comments have been posted.




.: Powered by Lore .:Code by WeCodeThings Website Design and Development