Click here to Skip to main content
15,888,579 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I have two tables and I want select all rows from first table and rows from second table with latest date. Example:

Table1

IDSome column
1sfafsda
2trwe
3gfdgsd


Table2

IDFK_Table1Date
1122.5.2014
211.2.2015
311.1.2015
421.1.2015
521.1.2013
631.1.2010


Table which I need:

IDTable1_IDTable2_IDDate
1121.2.2015
2241.1.2015
3361.1.2010


I was trying with this but that solution dont work for me:

SQL
 SELECT Table1.*, tmp.*
 FROM Table1
 LEFT JOIN (
 SELECT s.* FROM Table2 as s ORDER BY s.Date DESC
 ) as tmp ON Table1.ID = tmp.FK_Table1
GROUP BY Table1.ID


There is an error because "ORDER BY" clause -
ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.


Has anyone an idea to solve this problem (for MSSQL)?

Thanks!
Posted
Updated 18-Oct-15 4:38am
v3
Comments
Maciej Los 18-Oct-15 10:42am    
The error message is quite obvious.

1 solution

Try this:
SQL
SELECT t1.*, t2.*
FROM Table1 AS t1 LEFT JOIN Table2 AS t2 ON t1.ID = t2.FK_Table1
ORDER BY t2.Date DESC


In case you want to get only latest date, try this:
SQL
SELECT t1.*, t2.*
FROM Table1 AS t1 LEFT JOIN (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY FK_Table1 ORDER BY [Date] DESC) AS RowNo
    FROM Table2  
) AS t2 ON t1.ID = t2.FK_Table1 AND t2.RowNo=1


Tested on:
SQL
SET DATEFORMAT dmy;

DECLARE @table1 TABLE (ID INT,  SomeColumn VARCHAR(30))
INSERT INTO @table1 (ID, SomeColumn)
VALUES(1, 'sfafsda'),
(2, 'trwe'),
(3, 'gfdgsd')

DECLARE @table2 TABLE(ID INT, FK_Table1 INT, [Date] DATE)
INSERT INTO @table2 (ID, FK_Table1, [Date])
VALUES(1, 1, '22/05/2014'),
(2, 1, '01/02/2015'),
(3, 1, '01/01/2015'),
(4, 2, '01/01/2015'),
(5, 2, '01/01/2013'),
(6, 3, '01/01/2010')

SELECT t1.*, t2.*
FROM @table1 AS t1 LEFT JOIN (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY FK_Table1 ORDER BY [Date] DESC) AS RowNo
    FROM @table2
) AS t2 ON t1.ID = t2.FK_Table1 AND t2.RowNo=1
 
Share this answer
 
v5
Comments
[no name] 18-Oct-15 10:44am    
But this will give a result set with 6 lines... and OP Needs only the latest date I think.
Bruno
Maciej Los 18-Oct-15 10:46am    
Thank you, Bruno, for your valuable comment. Seems i missunderstood OP's question. I'll improve my answer soon.
[no name] 18-Oct-15 10:53am    
You are welcome. Anyway it seems there is no need of any join to get the result for this :)
Maciej Los 18-Oct-15 10:55am    
Yeah... Seems, OP need to "filter" only second table ;)
[no name] 18-Oct-15 11:04am    
Anyway a 5 for your effort to help OP. Bruno

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900