【问题标题】:Query to detect row type basing on the number of the row查询根据行数检测行类型
【发布时间】:2020-06-21 21:19:07
【问题描述】:

我有这张桌子:

有两种不同类型的记录:第三、第四和第五列为空的记录和只有第六列为空的记录。我需要一个查询(稍后我将插入到 php 代码中),它基于行数,允许我检测它是第一种类型的记录还是第二种类型的记录。例如,第 1 行--> 第一种类型,第 2 行--> 第一种类型,第 3 行--> 第二种类型,...有什么想法吗?

【问题讨论】:

  • 看看ROW_NUMBER()函数

标签: sql select


【解决方案1】:

您可以在这里使用CASE 表达式:

SELECT *,
    CASE WHEN email_cliente IS NULL
         THEN 1
         WHEN date_inizio IS NULL AND date_fine IS NULL AND id_prodotto IS NULL
         THEN 2 ELSE 3 END AS type
FROM yourTable;

【讨论】:

    【解决方案2】:

    请确保您没有将表格添加为屏幕截图。 这就是你所需要的,用真实姓名替换 col 值。如果只有两种类型,那么您只需要一个 case 语句来检查 3 列是否为 null。如果它们不是null,则记录属于第二种类型。

       select 
        col1,
        col2,
        case when col3 is null and col4 is null and col5 is null then 'second_type' else 'first_type' end
        from table 
    

    【讨论】:

      【解决方案3】:

      为简洁起见,您可以使用coalesce

       select *, case when coalesce (date_inizio, date_fine, id_prodotto) is null then 'type2' 
                      else 'type1' end as type
       from your_table;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        • 2013-08-31
        • 2016-09-04
        相关资源
        最近更新 更多