【问题标题】:I want to SELECT one column in three diferend ways to separate resultsI want to SELECT one column in three diferend ways to separate results
【发布时间】:2022-12-01 23:28:19
【问题描述】:

I have table with few columns but I am interested in two of them:

  1. name
  2. type - it can be one of tree values: 1, 2, 3

    All I want to create is a table where in first column I will SELECT value from column name where type = 1, in second column value from column name where type = 2, in last column value from column name where type = 3

    I tried to create a subquery (I want to do it via CTE) but I got an error about the subquery returns more than 1 value. I tried something with case clause but its not working anyway. I was thinking about UNION it but I am not sure.
    This is how the basic table looks like:

    SELECT name, type
    FROM table1
    

    Table:

    name type
    Product1 1
    Product2 2
    Product3 1
    Product4 3

    And how I want to see SELECT it:

    Product with type 1 Product with type 2 Product with type 3
    Product1 Product9 Product33
    Product5 Product11 Product41
    Product3 Product17 Product22
    Product7 Product20 Product23

    I just don't know how to show values with where type = 1 as one column, type = 2 as second column and type =3 as third.

【问题讨论】:

  • Can you provide us sample data and expected output?
  • @PauloFernando added in question
  • I haveassumedyou are using SQL Server here, however, if you are using a different product that uses T-SQL, such as Azure SQL Edge or SyBase, please edit your question to correct the tags.
  • @Larnu I am using SQL Server that's right nothing more

标签: sql sql-server tsql


【解决方案1】:

For MySQL;

SELECT
  IF(type=1, name, NULL) as "Product with type 1",
  IF(type=2, name, NULL) as "Product with type 2",
  IF(type=3, name, NULL) as "Product with type 3"
FROM table1

For T-SQL;

SELECT
  CASE WHEN type=1 THEN name ELSE NULL END as "Product with type 1",
  CASE WHEN type=2 THEN name ELSE NULL END as "Product with type 2",
  CASE WHEN type=3 THEN name ELSE NULL END as "Product with type 3"
FROM table1

【讨论】:

  • Ok I used IIF and its helped :) Thank you
猜你喜欢
  • 2022-12-28
  • 1970-01-01
  • 2022-12-02
  • 1970-01-01
  • 2022-12-02
  • 2022-11-20
  • 2022-11-20
  • 2022-11-09
  • 2022-12-02
相关资源
最近更新 更多