【问题标题】:SQL Group by with return boolean for anySQL Group by 并返回布尔值
【发布时间】:2015-03-26 14:09:42
【问题描述】:

我正在尝试进行分组并返回一个布尔值以判断分组是否包含组中的值。

我有两个表格 Title Table 和 Items Table。

Title.ID 是我的 Items 表的外键。

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

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.

我正在寻找一个类似于 Any(i.Formatcode = 'DOD') as hasDODItem 的函数

【问题讨论】:

    标签: sql sql-server group-by


    【解决方案1】:
    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
    

    或者您可以使用子查询和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
    

    【讨论】:

      【解决方案2】:

      使用case:

       Select t.ID, (case when i.Formatcode = 'DOD' then 1 else 0 end) as hasDODItem
       From Title t join
            Item i
            on i.TitleID = t.ID
       group by t.ID
      

      编辑:

      如果您只想知道具有特定项目的 ID,请使用 exists 而不是 join

       Select t.ID,
              (case when exists (select 1
                                 from item i
                                 where i.TitleID = t.ID and i.Formatcode = 'DOD' 
                                )
                    then 1 else 0 end) as hasDODItem
       From Title t ;
      

      join 不是必需的。我以为你出于某种原因想要它。

      【讨论】:

      • 我不需要一些如何包含将返回多行的 i.formatcode 吗?
      【解决方案3】:

      使用 EXISTS 查看 Formatcode = 'DOD' 是否存在:

      select t.ID, case when exists (select 1 from Item i
                                     where i.Formatcode = 'DOD'
                                     and i.TitleID = t.ID) then true else false end
      from Title t
      

      【讨论】:

        猜你喜欢
        • 2018-01-30
        • 1970-01-01
        • 2021-06-05
        • 1970-01-01
        • 2014-06-28
        • 2021-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多