比较sql中的两个int值

时间:2011-08-18 21:21:15

标签: sql-server tsql

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

我有两个不同的查询来获取这些值,我只是不知道如何比较:

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

我需要比较上面两个级别并获得两者中的较大者。

感谢

3 个答案:

答案 0 :(得分:2)

像(在我的头顶)的东西

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'

答案 1 :(得分:0)

你可以使用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

答案 2 :(得分:0)

如果表格不相关(或者您正在与两个不同的用户进行比较等),那么您可以采用一种方式:

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'