SQL group by syntax and example
Group by statement
The group by statement is used in combination with the aggregate function to group result sets based on one or more columns.
SQL group by syntax
Select column_name, aggregate_function (column_name)
From table_name
Where column_name operator value
Group by column_name
Let's look at a group by instance.
For example, the content in the table is as follows:
Gameid best top spam
111 1 1 1
121 1 1 0
123 0 1 1
111 1 0 1
The result of getting the best top spam number is
Gameid best top spam
111 2 1 2
121 1 1 0
123 0 1 1
Select gameid, sum (best) as bestcnt, sum (top) as tocnt, sum (spam) as spamcnt
From table
Group by gameid
How to use it in the php tutorial
$ SQL = "select gameid, sum (best) as best, sum (top) as top, sum (spam) as spam, from tablename group by gameid order by gameid asc ";
Let's look at a simple example.
Database tutorial table
Win or lose by date
-9 wins
-9 wins
2009-12-9 negative
2009-12-9 negative
2009-12-10 negative
-12-10 wins
2009-12-10 negative
Query Result
Date wins/loses
2009-12-9 2 2
2009-12-10 1 2
Select date,
Sum (decode (winning, winning )),
Sum (decode (winning or losing, 'negative ))
From database table
Group by date