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