Use IF in SELECT part of query

wingyip

I need to create something like this

SELECT x.id
   , x.name
   , x.type
   ,(
      IF x.type = 1
         (SELECT SUM(Col1) FROM TableA WHERE ... etc)
      ELSE IF x.type = 2
         (SELECT SUM(Col2) FROM TableB WHERE ... etc)
    ) AS Total
FROM TableX as x

So I am trying to select a different sub query according to the value of x.type

Wing

Pரதீப்

Use CASE statement

SELECT x.id,
       x.name,
       x.type,
       CASE
         WHEN x.type = 1 THEN (SELECT Sum(Col1)
                               FROM   TableA Where...)
         WHEN x.type = 2 THEN (SELECT Sum(Col2)
                               FROM   TableB  Where .. )
       END AS Total
FROM   TableX AS x 

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Django - Use model fields part in a create or update query

Django - Use model fields part in a create or update query

How to use select query inside max function?

Select part of value in one column and copy it to another column - sql query

How to Use HAVING in a Subquery as Part of a Select Statement

SQL Server : How to use XPATH in select query

How do I use a sub query in the SELECT part with DBIx::Class?

Replace part of a column value in MySQL Select query

Use one select query instead of query + subquery

codeigniter use part of query result in another query

How to use a default in SELECT query?

Pandas: how to use query to select closest values

How use an array/implode in the SELECT query PDO

select query based on time part of the datetime field

How to select a specific part of a SQL query result?

MySQL - How to use file name as a part of Query?

How to use combination Select Query and update query?

Use result of 'IF' in 'SELECT' in 'WHERE' clause in SQL query

How to use a function in Select Query

Appending to the Select part of a query

How to return part of a string from a mysql table filed by select query?

select count(*) as part of larger select query

Use dynamic parameter in SELECT query in Postgres?

MySQL: Use select in update query

How to use a parameter to select which query to use?

Use MySQL variable only for counting without returning to client in SELECT part

How do I use label in this part of this query?

How use SELECT in append query in Access SQL?

Ok to use select in where query?

TOP Ranking

HotTag

Archive