Three (3) Steps on How to Count Values With MySql Queries

0
62

This tutorial is all about Three (3) Steps on How to Count Values With MySql Queries.
This is a very simple tutorial on how to create a queries that Counts the values using MySql query. For instance, if your going to create a voting system application that requires counting the number of votes by candidate you do not have to use loops in looping through all the rows but instead you can do it using simple query.

 

To demonstrate this, you need to follow this instruction.

 

Step 1: Create a table in your database.

  1. CREATE TABLE `test`.`tblvoting` (
  2. `POLITICIAN` VARCHAR( 30 ) NOT NULL ,
  3. `VOTES` INT( 11 ) NOT NULL DEFAULT '0'

Step 2: Populate the table.

  1. INSERT INTO `tblvoting` (`ID`, `POLITICIAN`, `VOTES`) VALUES
  2. (1, 'MAR', 1),
  3. (2, 'DUTERTE', 1),
  4. (3, 'DUTERTE', 0),
  5. (4, 'DUTERTE', 1),
  6. (5, 'DUTERTE', 1),
  7. (6, 'DUTERTE', 0),
  8. (7, 'DUTERTE', 1),
  9. (8, 'DUTERTE', 1),
  10. (9, 'DUTERTE', 0),
  11. (10, 'DUTERTE', 1),
  12. (11, 'DUTERTE', 1),
  13. (12, 'DUTERTE', 1),
  14. (13, 'MAR', 1),
  15. (14, 'DUTERTE', 1),
  16. (15, 'MAR', 0),
  17. (16, 'DUTERTE', 1),
  18. (17, 'BINAY', 1),
  19. (18, 'BINAY', 1),
  20. (19, 'BINAY', 1),
  21. (20, 'DUTERTE', 0),
  22. (21, 'BINAY', 1),
  23. (22, 'MAR', 1),
  24. (23, 'POE', 1),
  25. (24, 'DUTERTE', 1),
  26. (25, 'POE', 0),
  27. (26, 'POE', 1),
  28. (27, 'POE', 1),
  29. (28, 'BINAY', 1),
  30. (29, 'BINAY', 0),
  31. (30, 'DUTERTE', 1),
  32. (31, 'BINAY', 1),
  33. (32, 'MAR', 1);

Step 3:  Create a query that will do the job for counting all the number of votes by Candidate.

  1. SELECT `POLITICIAN` , SUM( `VOTES` ) AS 'Total Votes earned', COUNT( `VOTES` ) AS `total`
  2. FROM tblvoting
  3. GROUP BY `POLITICIAN`
  4. ORDER BY `VOTES` DESC

The following would be the result of query in Step 3:

POLITICIAN Total Votes earned total
BINAY 6 7
POE 3 4
MAR 4 5
DUTERTE 12 16

Explanation:

What happen to the query in Step 3 , is that we use SUM Function to sum all the votes then we all use COUNT Function to keeps a tally on the total number of votes. Finally, the GROUP BY `POLITICIAN` statement allows the vote counters to calculate the numbers by POLITICIAN.

 

Readers might read also:

Facebook Comments
(Visited 18 times, 1 visits today)

LEAVE A REPLY

Please enter your comment!
Please enter your name here