【问题标题】:Return value based on count in a case query案例查询中基于计数的返回值
【发布时间】:2021-06-11 06:19:30
【问题描述】:

我很期待你对这个请求的意见,看起来超级简单,但我一个人想不通。

如果表列part_status有一个值,则返回;否则返回“很多”。

场景 1 表格数据:

Part_Status
'A'
'A'
'A'

返回

Part_Status
'A'

场景2表格数据:

Part_Status
'A'

在此处返回 col1 值

Part_Status
'A'

场景 3 表格数据:

Part_Status
'A'
'E'

返回值

Part_Status
'Many'

第一个想法是用例,如果计数的数量大于 1,则返回 'many' 但从不打印:

select DISTINCT case
     when count(PART_STATUS) > 1 THEN
      'MANY'
     ELSE
      PART_STATUS
   end
from (select DISTINCT Part_Status
      from Inventory_Part
     where part_status IN ('A','E')
     )
GROUP BY PART_STATUS

返回

Part_Status
'A'
'E'

在第二个想法中,我得到了 'Many' 工作,但单个结果为 NULL

select CASE
     WHEN COUNT(PART_STATUS) > 1 THEN
      'Many'
   end AS "PART_STATUS"
FROM (select DISTINCT Part_Status
      from Inventory_Part
     where part_status IN ('A', 'E'))

返回

Part_Status 
'Many'

那么,如何将两者结合起来呢?

【问题讨论】:

    标签: oracle select count case


    【解决方案1】:

    我可以解决它。无论如何,我不相信这是聪明的方法。

    select CASE
             when "cnt" > 1 THEN
              'Many'
             when "cnt" = 1 THEN
              PART_STATUS
           end
      from (select rownum AS "cnt", PART_STATUS
              FROM (select DISTINCT Part_Status
                      from Inventory_Part
                     where part_status IN ('A', 'E'))
             ORDER BY ROWNUM DESC)
    
     fetch first row only
    

    【讨论】:

      【解决方案2】:

      这样的?

      SQL> with test (part_status) as
        2    (select 'A' from dual union all
        3     select 'A' from dual
        4    )
        5  select distinct
        6         case when (select count(distinct part_status) from test) > 1 then 'Many'
        7              else part_status
        8         end
        9  from test;
      
      CASE
      ----
      A
      

      SQL> with test (part_status) as
        2    (select 'A' from dual union all
        3     select 'E' from dual
        4    )
        5  select distinct
        6         case when (select count(distinct part_status) from test) > 1 then 'Many'
        7              else part_status
        8         end
        9  from test;
      
      CASE
      ----
      Many
      
      SQL>
      

      【讨论】:

      • 让我检查一下。今天晚些时候我会回来找你的!谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多