SQL GROUP BY syntax and instance

Source: Internet
Author: User
Tags php tutorial

SQL GROUP BY syntax and instance

GROUP BY statement

The GROUP BY statement is used to combine aggregate functions 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

To see a group by instance

Like the contents of the table.

GameID Best Top spam

111 1 1 1

121 1 1 0

123 0 1 1

111 1 0 1

I'm going to take out the best top spam The number result should be

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

Using methods 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 simpler example.

Database Tutorial Tables Table

Date wins

2009-12-9 wins

2009-12-9 wins

2009-12-9 Negative

2009-12-9 Negative

2009-12-10 Negative

2009-12-10 wins

2009-12-10 Negative

Query results

Date wins

2009-12-9 2 2

2009-12-10 1 2

Select Date,

SUM (Decode (winner, ' win ', 1,0)),

SUM (Decode (winner, ' negative ', 1,0))

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.