sql-获取BIT列的MAX值

我在联接表中有一个带有“内部联接”的SELECT请求,是一列具有位类型的列。

如果联接表中的值最多为1,我想选择1。如果不是,则值为0。

所以,如果我有:

PERSID | NAME
1      |  Toto
2      |  Titi
3      |  Tata

还有第二张桌子

PERSID | BOOL
1      |  0
1      |  0
2      |  0
2      |  1

我想得到结果

Toto -> 0
Titi -> 1
Tata -> 0

我尝试这样:

SELECT 
     sur.*
    ,MAX(bo.BOOL)    

    FROM SURNAME sur              
    INNER JOIN BOOL bo
    ON bo.IDPERS = sur.IDPERS

但是MAX在BIT列上不可用。那么我该怎么做?

谢谢,

5个解决方案
69 votes

您可以将其投放到INT,如果需要,甚至可以将其投放回BIT

SELECT 
     sur.*
    ,CAST(MAX(CAST(bo.BOOL as INT)) AS BIT)
    FROM SURNAME sur              
    INNER JOIN BOOL bo
    ON bo.IDPERS = sur.IDPERS
kenwarner answered 2020-06-27T16:06:09Z
12 votes

尝试:

max(cast(bo.BOOL as int))
Andomar answered 2020-06-27T16:06:29Z
6 votes

单程

SELECT 
     sur.*
    ,MAX(convert(tinyint,bo.BOOL))    

    FROM SURNAME sur              
    INNER JOIN BOOL bo
    ON bo.IDPERS = sur.IDPERS
SQLMenace answered 2020-06-27T16:06:49Z
3 votes

您可以通过强制执行隐式强制转换来避免看上去凌乱的双重强制转换:

SELECT 
     sur.*
    ,CAST(MAX(1 * bo.BOOL) AS BIT)
    FROM SURNAME sur              
    INNER JOIN BOOL bo
    ON bo.IDPERS = sur.IDPERS
Stuart Steedman answered 2020-06-27T16:07:09Z
1 votes

如果只希望那些只有一位的人:

declare @Surname as Table ( PersId Int, Name VarChar(10) )
insert into @Surname ( PersId, Name ) values
  ( 1, 'Toto' ), ( 2, 'Titi' ), ( 3, 'Tata' ), ( 4, 'Tutu' )

declare @Bool as Table ( PersId Int, Bool Bit )
insert into @Bool ( PersId, Bool ) values
  ( 1, 0 ), ( 1, 0 ),
  ( 2, 0 ), ( 2, 1 ),
  ( 4, 1 ), ( 4, 0 ), ( 4, 1 )

select Sur.PersId, Sur.Name, Sum( Cast( Bo.Bool as Int ) ) as [Sum],
  case Sum( Cast( Bo.Bool as Int ) )
    when 1 then 1
    else 0
    end as [Only One]
  from @Surname as Sur left outer join
    @Bool as Bo on Bo.PersId = Sur.PersId
  group by Sur.PersId, Sur.Name
  order by Sur.Name
HABO answered 2020-06-27T16:07:29Z
translate from https://stackoverflow.com:/questions/10803968/get-max-value-of-a-bit-column