簡體   English   中英

SQL case return 多於 1 行 寫一個字符串

[英]SQL case return more than 1 row write a string

我在 SELECT 中有一個子查詢,有時它返回不止一行。 我想解決這樣的問題:

  • 當超過 1 行寫一個字符串,如 'multi'
  • 否則使用注釋表中的值描述

詢問:

select 
    s.id, 
    (select description from comment c where c.id = s.id) 
from student s;

謝謝。

您可以加入、聚合和使用條件表達式:

select 
    s.id,
    case when min(c.description) <> max(c.description) 
        then 'multi' 
        else min(c.description) 
    end description
from student s
left join comment c on c.id = s.id
group by s.id

您也可以使用子查詢來執行此操作,從而避免外部聚合(如果您需要來自students的更多列,這很方便):

select
    s.*,
    (
        select 
            case when min(c.description) <> max(c.description) 
                then 'multi' 
                else min(c.description) 
            end
        from comment c
        where c.id = s.id
    ) description
from student s

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM