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

0
184

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.

[mysql]

CREATE TABLE test.tblvoting (
ID INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
POLITICIAN VARCHAR( 30 ) NOT NULL ,
VOTES INT( 11 ) NOT NULL DEFAULT ‘0’
) ENGINE = INNODB;

[/mysql]

Step 2: Populate the table.

[mysql]

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

[/mysql]

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

[mysql] SELECT POLITICIAN , SUM( VOTES ) AS ‘Total Votes earned’, COUNT( VOTES ) AS total
FROM tblvoting
GROUP BY POLITICIAN
ORDER BY VOTES DESC
[/mysql] 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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.