SQL conditional AVG Function Application

Source: Internet
Author: User

 

Today, I encountered a problem. I need to query the average value of col2 with col1 = 1 from several associated tables, that is, to AVG (...) The objects in the brackets should be named filtering conditions. Instead of calculating the average value of all objects, the average value of the objects that meet certain conditions is calculated.

I tried several methods, tried to use subqueries, tried to change the connection structure, and did not achieve the expected results. After reading some information, I found a method, it is to use case to add conditions to the objects in AVG.

The query statement is as follows:

Select AVG (case when col1 = 1 then the col2 end) form tablename

The above statements show the desired results. In fact, SQL is very powerful. As long as we can make full use of SQL functions, we can save a lot of code.

Case has two formats. Simple case functions and case search functions.

-- Simple case function case sexwhen '1' then' male 'when' 2' then' female 'else' other 'ends -- case search function case when sex = '1' then' male 'When sex = '2' then' female 'else' others' end

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.