SQL makes multiple statistics on a table according to different conditions

Source: Internet
Author: User

Recently has been doing data statistics, in the process, encountered a good many situations are a table according to different conditions for multiple statistics, the previous practice is to count several times according to different conditions left join several times, although also can get the desired results, but the efficiency is too low, reflected in the page is very slow access.

Today in another encounter this situation, to a table according to different conditions to carry out seven or eight statistics, do not want in accordance with the previous ideas, in the online search, if you can use cases when the statement to statistics, the specific idea is as follows:

The first step: according to the common data, query out all the data, including the number of fields to be counted

The second step is to include the case in the Count function and then the mechanical write.

The third step: to see such a high efficiency, oneself in the side to steal the music.

Not much to say, on the code

--There is a table table1 field there id,name,sex,age--now requires statistics on the number of males, number of females, age 25, number of persons aged 26 select count (case when               sex = ' gril ' then                1             end) Number of females,       count (case if               sex = ' gril ' then                1             end) Number of females,       count (               case                1             end) Number of people aged 25,       count (case if                age = 1             end) 26 years old from  table1 where 1 = 1

  

SQL makes multiple statistics on a table according to different conditions

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.