How to Create Two Columns from One Column in SQL Based on a IF argument in Another Column

Cem Yilmaz :

I have a table that has 3 columns. Value, condition and day. I would like to SELECT two columns from column Value. One which is average value of t.value grouped by t.condition 1 and another one which is an average value of t.value grouped by t.condition 2. I would then like to group them all by day and condition.

Table

Result should look like this table.

expected result

I have tried case when, if and CTEs. However, they all failed. The if statement work for fulfilling one condition but seeing that condition is binary, the if function i tried did not work. I have considered creating two tables and then joining on day. That would work I would assume. Would there be an easier way of doing this?

Thank you!

Gordon Linoff :

You can use conditional aggregation:

select day,
       max(case when condition = 1 then value end) as value_1,
       max(case when condition = 2 then value end) as value_2
from t
group by day;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=386784&siteId=1