SQL group by syntax and example

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.