Skip to content
Advertisement

How to set flag to true and also get the total while grouping

Table

|C1    |C2  |C3     |
|------|----|-------|
|A     |M   |4000   |
|A     |S   |588998 |
|B     |S   |2      |
|      |    |       | 

Output as

|C1   |Total of C3|Flag set to true if C1 contains only S as Status|
|-----|--------   |-------                                         |
|A    |592998     |0                                               |
|B    |2          |1                                               | 
                        

                                                

Thank you in Advance

Advertisement

Answer

Use conditional aggregation:

select c1, sum(c3),
       min(case when c2 = 'S' then 1 else 0 end) as flag
from t
group by c1;

You can also express the condition as:

select c1, sum(c3),
      (case when min(c2) = max(c2) and min(c2) = 'S' then 1 else 0 end) as flag
from t
group by c1;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement