Select statement inside CASE-SQL

I am trying to figure out the correct code for the logic below. If the first column has a specific value, display the value from the second column for this particular record. Can someone help? Thank.

CASE WHEN TableA.Column1 = 'a' THEN 'select TableA.Column2 '
     WHEN TableA.Column4 = 'b' THEN 'select TableA.Column5'

     ELSE TableA.Column6
END AS [Test]
+4
source share
4 answers

You almost simply deleted selectfrom case statement. Since all values ​​come from the same table, there is no need select, if the case statement just saves column name, it will get the corresponding column value.

SELECT CASE
         WHEN Column1 = 'a' THEN Column2
         WHEN Column4 = 'b' THEN Column5
         ELSE Column6
       END AS [Test]
FROM   tableA 
+6
source

Try the following:

SELECT (CASE WHEN A.Column1 = 'a' THEN A.Column2
             WHEN A.Column4 = 'b' THEN A.Column5
             ELSE A.Column6
        END) AS [Test]
FROM TableA A;
+1
source

SELECT, SELECT :

SELECT
    ...
,   CASE WHEN TableA.Column1 = 'a' THEN TableA.Column2
         WHEN TableA.Column4 = 'b' THEN TableA.Column5

         ELSE TableA.Column6
    END AS [Test]
FROM
    TableA
...
+1

:

select CASE WHEN TableA.Column1 = 'a' THEN TableA.Column2
     WHEN TableA.Column4 = 'b' THEN TableA.Column5
     ELSE TableA.Column6
END AS [Test]
from tableA

:

select CASE TableA.Column1 
     WHEN 'a' THEN TableA.Column2
     WHEN 'b' THEN TableA.Column5
     ELSE TableA.Column6
END AS [Test]
from tableA
0
source

Source: https://habr.com/ru/post/1569552/


All Articles