SQL Group by with return boolean for any

3 sql sql-server group-by

我正在尝试进行分组并返回一个布尔值,表示group by是否包含组中的值.

我有两个表标题表和项目表.

Title.ID是我的Items Table的外键.

我的项目表有多个格式代码,如果一个组包含格式代码,我需要选择一个布尔值

Sql语句如下所示:

 Select t.ID, Any(i.Formatcode = 'DOD') as hasDODItem
 From Title t
 join Item i on i.TitleID = t.ID
 group by t.ID.
Run Code Online (Sandbox Code Playgroud)

我正在寻找一个像Any(i.Formatcode ='DOD')一样的函数作为hasDODItem

Rom*_*kar 5

select t.ID, max(case when i.Formatcode = 'DOD' then 1 else 0) as hasDODItem
from Title as t
    inner join Item as i on i.TitleID = t.ID
group by t.ID
Run Code Online (Sandbox Code Playgroud)

或者您可以使用子查询执行此操作exists:

select
    t.ID,
    case
        when exists (
            select *
            from Item as i
            where i.TitleID = t.ID and i.Formatcode = 'DOD'
        ) then 1
        else 0
    end as hasDODItem
from Title as t
Run Code Online (Sandbox Code Playgroud)