case condition

Shambhu Rai 1,406 Reputation points
2023-06-09T13:44:15.1866667+00:00

Hi Expert,

the below is the condition

case when oid= 'Winter' then Name else 'noname'

create table table1(id varchar(30), name varchar(30), oid varchar(30))

insert into table1 values('1', 'David', 'Winter')

insert into table1 values('2', 'Hash', 'Winter')

insert into table1 values('3', 'Steve', 'Autumn')

Expected output

('1', 'David', 'Winter')

('2', 'Hash', 'Winter')

('3', 'noname', 'Autumn')

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,639 questions
SQL Server Reporting Services
SQL Server Reporting Services
A SQL Server technology that supports the creation, management, and delivery of both traditional, paper-oriented reports and interactive, web-based reports.
2,790 questions
SQL Server Integration Services
SQL Server Integration Services
A Microsoft platform for building enterprise-level data integration and data transformations solutions.
2,450 questions
SQL Server Analysis Services
SQL Server Analysis Services
A Microsoft online analytical data engine used in decision support and business analytics, providing the analytical data for business reports and client applications such as Power BI, Excel, Reporting Services reports, and other data visualization tools.
1,242 questions
{count} votes

7 answers

Sort by: Most helpful
  1. Jingyang Li 5,891 Reputation points
    2023-06-09T13:52:37.8266667+00:00

    select id,

    case when oid= 'Winter' then Name else 'noname' end name

    ,oid

    from table1


  2. Samy Abdul 3,366 Reputation points
    2023-06-09T14:03:07.2166667+00:00

    Hi @Shambhu Rai ,The case statement syntax should be as follows:

    SELECT column1,
                 column2,
                   CASE WHEN CONDITION THEN 'Value1'
                   ELSE 'Value2' END AS columnX
      FROM Products
    
    

  3. Shambhu Rai 1,406 Reputation points
    2023-06-09T14:43:16.8733333+00:00

    Any other suggestion please

    0 comments No comments

  4. Bruce (SqlWork.com) 54,866 Reputation points
    2023-06-10T00:07:33.8266667+00:00

    You have been given the correct answer for the sql query. If you are not getting the correct results, then must be more you are not telling us.

    0 comments No comments

  5. Samy Abdul 3,366 Reputation points
    2023-06-10T05:08:55.5066667+00:00

    Hi @Shambhu Rai, please try this. This is giving expected output. Thanks

    SELECT id, CASE id WHEN '3' THEN 'noname' ELSE name END AS name,‎
    	CASE id WHEN '3' THEN 'Autumn' ELSE oid END AS oid ‎
    FROM table1;‎
    
    
    0 comments No comments