Spandan Pathak
Spandan Pathak

Reputation: 37

Create SQL query with given Conditions

I have an SQL query of the form

SELECT 
    SUM(some_col) 
FROM
    (some table name here)
WHERE 
    some_common_condition AND
    some_condition1 AND 
    some_condition2 AND
    column_A = 'X'
GROUP BY 
    column_A;

column_A has some values for which I currently run this query for. Now for each of the unique values of column_A there are some associated conditions.

For eg, if column_A has 3 unique values X,Y,Z, all three have some_common_condition and some specific conditions associated with it,i.e,

I want to club all these conditions and make 1 single SQL query,which gives me corresponding SUM(some_col) for all the values of column_A (i.e. X,Y,Z).

Now one obvious way is

SELECT *
  FROM(SELECT SUM(some_col) AS val_X FROM (table) WHERE conditions_for_X UNION ALL
       SELECT SUM(some_col) AS val_Y FROM (table) WHERE conditions_for_X UNION ALL
       SELECT SUM(some_col) AS val_Z FROM (table) WHERE conditions_for_X -- UNION ALL a.s.o.
      )

I want to know a solution which only hits the database once. Above query uses 3 select statements, hitting the DB three times, which is bad for scalability reasons.

Upvotes: 1

Views: 64

Answers (1)

Tzach
Tzach

Reputation: 13396

Does this answer your question?

SELECT SUM(some_col) FROM ...

WHERE 
  (column_A = 'X' AND some_condition1 AND some_condition2) OR
  (column_A = 'Y' AND some_condition3 AND some_condition4) OR
  (column_A = 'Z' AND some_condition5 AND some_condition6)

GROUP BY column_A;

Upvotes: 2

Related Questions