2011-08-18 88 views
3

我該如何解決從表中的列中獲取值並將其與另一個表中的列進行比較並在單個查詢中返回兩者中的較大者?比較tsql中的兩個int值

我爲得到這些值的兩個不同的問題,我只是不知道如何比較:

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

我需要比較上述兩個層次,並獲得兩個大。

感謝

回答

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' 
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 
0

如果表是不是聽上去很像(或者如果你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'