60

我有一个 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 列上不可用。那么我该怎么做呢?

谢谢,

4

5 回答 5

90

您可以将其转换为 a ,如果需要INT,甚至可以将其转换回 aBIT

SELECT 
     sur.*
    ,CAST(MAX(CAST(bo.BOOL as INT)) AS BIT)
    FROM SURNAME sur              
    INNER JOIN BOOL bo
    ON bo.IDPERS = sur.IDPERS
于 2012-05-29T17:37:01.007 回答
18

尝试:

max(cast(bo.BOOL as int))
于 2012-05-29T17:36:24.600 回答
7

单程

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

    FROM SURNAME sur              
    INNER JOIN BOOL bo
    ON bo.IDPERS = sur.IDPERS
于 2012-05-29T17:37:44.990 回答
6

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

SELECT 
     sur.*
    ,CAST(MAX(1 * bo.BOOL) AS BIT)
    FROM SURNAME sur              
    INNER JOIN BOOL bo
    ON bo.IDPERS = sur.IDPERS
于 2018-10-04T12:37:40.320 回答
1

如果您只想要那些只有一个设置位的人:

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
于 2012-05-29T18:13:11.700 回答