SQL组和排序依据

时间:2015-08-20 21:33:06

标签: sql sql-server sql-order-by greatest-n-per-group sql-subselect

好吧,我有一个SQL表,如下所示:

Name title dept salary
Abc aaaa qazwsx 15
Abc aaaa hehene 73
Abc aaaa geneh 55
Abc bbbb thghbh 33
Abc bbbb hehehe 433
Abc bbbb eyehhe 54

创建数据的声明 -

CREATE TABLE #StackOverflow
(Name VARCHAR(5)
,Title VARCHAR(5)
, Dept VARCHAR(10)
, Salary INT);

INSERT INTO #StackOverflow
(Name, Title, Dept, Salary)
SELECT 'Abc', 'aaaa', 'qazwsx', 15  UNION ALL
SELECT 'Abc', 'aaaa', 'hehene', 73  UNION ALL
SELECT 'Abc', 'aaaa', 'geneh', 55   UNION ALL
SELECT 'Abc', 'bbbb', 'thghbh', 33  UNION ALL
SELECT 'Abc', 'bbbb', 'hehehe', 433 UNION ALL
SELECT 'Abc', 'bbbb', 'eyehhe', 54

我需要编写一个查询,它会为我提供名称为abc且标题为aaaa的前2个部分,其名称为abc,标题为bbbb 。这应该按薪水排序!

如何使用SQL子查询实现它?

2 个答案:

答案 0 :(得分:2)

;WITH X AS 
 (
  SELECT * 
       ,ROW_NUMBER() OVER (PARTITION BY Name, Title
                           ORDER BY Salary DESC) rn 
  FROM TableName 
 )
SELECT * 
FROM x 
WHERE rn <= 2

答案 1 :(得分:-1)

Messages.properties