比较tsql中的两个int值

问题描述:

我该如何解决从表中的列中获取值并将其与另一个表中的列进行比较并在单个查询中返回两者中的较大者?比较tsql中的两个int值

我为得到这些值的两个不同的问题,我只是不知道如何比较:

select level from cmh where user = 'blah' 
select level from cons where user = 'blah' 

我需要比较上述两个层次,并获得两个大。

感谢

喜欢的东西(把我的头顶部)

select 
case when cmh.level > cons.level 
then cmh.level 
else cons.level 
end 
from cmh inner join cons on cmh.[user] = cons.[user] 
where cons.[user] = 'blah' 

你可以使用UNION连接两个查询,然后使用MAX()来获得水平的更大。

select max(level) as level 
from (
    select level from cmh where user = 'blah' 
    union all 
    select level from cons where user = 'blah' 
    ) as result 

如果表是不是听上去很像(或者如果你comparring两个不同的用户,等等),其中一个方法,你可以做到这一点:

Declare @var1 as int 
Declare @var2 as int 

SET @var1 = (select level from cmh where user = 'blah') 
SET @var2 = (select level from cons where user = 'blah') 

SELECT 
CASE WHEN isnull(@var1,0) >= isnull(@var2,0) THEN @var1 ELSE @var2 END 

否则,你可能涉及的表,像这样得到整个数据集:

SELECT 
    CASE WHEN isnull(T1.level,0) >= isnull(T2.level,0) THEN @var1 ELSE @var2 END as [greatest] 
FROM 
    cmh T1 LEFT JOIN cons T2 
    ON T1.user = T2.user 
WHERE T1.user = 'blah'