0

Well, I have a SQL table that is as below:

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

Statement to create data -

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

I need to write a query which will give me the top 2 depts whose name are abc and title is aaaa , whose name is abc and title is bbbb. This should be ordered by salary!

How do I implement it using SQL sub queries?

dar ka
  • 9
  • 1

2 Answers2

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
M.Ali
  • 67,945
  • 13
  • 101
  • 127
-1
SELECT TOP 2 dept
   FROM table 
   WHERE name='abc' AND title='aaaa'
   ORDER BY salary DESC;
asdf
  • 2,927
  • 2
  • 21
  • 42