我有一个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
但是BIT列上没有MAX ..那我怎么能这样做呢?
谢谢,
答案 0 :(得分:62)
您可以将其投放到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
答案 1 :(得分:10)
尝试:
max(cast(bo.BOOL as int))
答案 2 :(得分:5)
单程
SELECT
sur.*
,MAX(convert(tinyint,bo.BOOL))
FROM SURNAME sur
INNER JOIN BOOL bo
ON bo.IDPERS = sur.IDPERS
答案 3 :(得分:3)
您可以通过强制执行隐式强制转换来避免看上去凌乱的双重强制转换:
SELECT
sur.*
,CAST(MAX(1 * bo.BOOL) AS BIT)
FROM SURNAME sur
INNER JOIN BOOL bo
ON bo.IDPERS = sur.IDPERS
答案 4 :(得分: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