2012-03-04 62 views
0

使用集合函數我已經已經以下數據最高/最低值,而無需在SQL

DNO DNAME SALARY 
20 EE 30000 
10 DoC 50000 
30 ITS 20000 

我想選擇與最大和最小薪水僱員WITHOUT使用GROUP功能或頂部 - 正分析名爲department表,或NOT EXISTS命令。任何幫助將不勝感激。謝謝

+0

爲什麼你想要這個? – 2012-03-04 11:02:30

+0

面試問題,我猜? – 2012-03-04 11:03:27

+0

僅用於研究目的 – user841852 2012-03-04 11:03:29

回答

8

最大。工資:

SELECT * 
FROM department d1 
WHERE salary > ALL (SELECT d2.salary 
        FROM department d2 
        WHERE d2.dno <> d1.dno) 

對於分鐘工資:

SELECT * 
FROM department d1 
WHERE salary < ALL (SELECT d2.salary 
        FROM department d2 
        WHERE d2.dno <> d1.dno) 

兩種解決方案都假設工資不能爲空

0
set nocount on 
declare @table table (
    val int 
) 

insert @table values (17) 
insert @table values (31) 
insert @table values (8) 
insert @table values (79) 
insert @table values (25) 
insert @table values (13) 

select * from @table 

select * from @table t where 1 = (select count(distinct val) from @table where t.val >= val) 
select * from @table t where 1 = (select count(distinct val) from @table where t.val <= val) 
3

你可以只是加入做到這一點,如果你不想使用任何更復雜的操作員。

SELECT * 
    FROM SO.dbo.MaxNoAgg mna1 
LEFT JOIN SO.dbo.MaxNoAgg mna2 ON (mna2.salary > mna1.salary) 
WHERE mna2.mna_id IS NULL; 

這基本上會給你沒有更高薪水的行存在的行。當然,它仍然會給出所有具有最大值的行(SELECT DISTINCT mna1.salary)。