Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Using DENSE_RANK with more than one table?

Author  Topic 

Rasta Pickles
Posting Yak Master

174 Posts

Posted - 2014-11-12 : 05:43:21
Hope someone can help, you guys usually have the answers :-)

I have two tables and I'm using DENSE_RANK to only retrieve the most recent record from one of them. I need to bring in a value from a second table, anyone know how?

Here's some sample code:

DECLARE @paytype AS TABLE (PayNo INT, PayrollNo INT, Pay DECIMAL (25, 10))
INSERT INTO @paytype
VALUES (1, 10000, 1200.00),
(2, 10000, 1300.00),
(3, 10000, 1250.00),
(4, 10100, 2000.00),
(5, 10100, 2200.00),
(6, 10100, 2550.00),
(7, 10200, 1000.00),
(8, 10200, 1100.00),
(9, 10200, 1200.00)

DECLARE @unit AS TABLE (PayrollNo INT, Unit INT)
INSERT INTO @unit
VALUES (10000, 475),
(10100, 566),
(10200, 575)

SELECT PayRollNo, Pay FROM
(SELECT PayNo, PayrollNo, Pay,
DENSE_RANK() OVER (PARTITION BY PayrollNo ORDER BY PayNo DESC, Pay DESC) RANK
FROM @paytype) X
WHERE RANK = 1


I want to bring in the unit so my output would look like:

PayRollNo Pay Unit
10000 1250.0000000000 475
10100 2550.0000000000 566
10200 1200.0000000000 575


Any pointers appreciated.

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2014-11-12 : 06:52:42
[code]SELECT X.PayrollNo, X.Pay, U.Unit
FROM
(
SELECT PayNo, PayrollNo, Pay,
DENSE_RANK() OVER (PARTITION BY PayrollNo ORDER BY PayNo DESC, Pay DESC) RANK
FROM @paytype
) X
INNER JOIN @unit U on X.PayrollNo = U.PayrollNo
WHERE RANK = 1
[/code]


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page
   

- Advertisement -