0

My table has 4 columns (name, A, B, C).

I need to build a query that has the following logic:

Select name,
    a as value1,
    b or c as value2
from table

Logic:

A <> ''
If B <> '' 
    then value2 = b else 
    if c <> '' then value2 = c 
        else value2 = '' 
1

1 Answer 1

5

Not sure what you meant by A <> ''; but here is an example that should give you the right idea at least.

USE [tempdb] ;
GO

CREATE TABLE [dbo].[tbl]
(
    [name] VARCHAR(15) NULL
  , [A]    VARCHAR(15) NULL
  , [B]    VARCHAR(15) NULL
  , [C]    VARCHAR(15) NULL  
);
GO

INSERT INTO [dbo].[tbl] VALUES ('name1','A1','','');
INSERT INTO [dbo].[tbl] VALUES ('name2','A2','','C2');
INSERT INTO [dbo].[tbl] VALUES ('name3','','B3','C3');
GO

SELECT
    [name]
  , [A] AS value1
  , CASE WHEN [B] <> '' THEN [B]
         WHEN [C] <> '' THEN [C]
         ELSE ''
    END AS value2
FROM
    [dbo].[tbl];
GO

-- Clean up
DROP TABLE [dbo].[tbl];
GO

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.