Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically choose one of two columns based on a third column [duplicate]

Tags:

sql

postgresql

I have 3 tables, lets say tables A, B, C to obfuscate my software :). A and B have two columns with numeric values and Table C has a Boolean column.

What I want is to create a view with a single column where depending on the column in C, either the value in A or B is selected.

Example:

Input:

        | A.val |    | B.val |    | C.val |
        ---------    ---------    ---------
entry1  |   1   |    |   6   |    |   T   |
entry2  |   2   |    |   8   |    |   F   |

Output:

       | D |
       -----
entry1 | 1 |
entry2 | 8 |

I'm wondering if there is a way to do this in a SQL statement(s) since I am currently doing it programmatically which eats up unnecessary resources.

like image 461
mascoj Avatar asked Sep 15 '15 21:09

mascoj


People also ask

How do you find duplicate records in a table with multiple columns?

Using the GROUP BY clause to group all rows by the target column(s) – i.e. the column(s) you want to check for duplicate values on. Using the COUNT function in the HAVING clause to check if any of the groups have more than 1 entry; those would be the duplicate values.

How do I check if two columns have the same value in SQL?

In SQL, problems require us to compare two columns for equality to achieve certain desired results. This can be achieved through the use of the =(equal to) operator between 2 columns names to be compared.


1 Answers

If you're trying to select A if C = T or B if C = F then you can just use a Case Statement

Select (Case When C.val = TRUE Then A.val Else B.Val END) AS D
From Table
like image 67
JamieD77 Avatar answered Oct 11 '22 00:10

JamieD77