2014-02-05 29 views
1

我有這個表:加入兩個表中的數據和頂部從表2

表1:

id Name 
1 Example1 
2 Example2 

表2:

id Date.............. 
1 5.2.2014........ 
1 6.2.2014......... 
1 6.2.2014........ 
2 16.1.2014....... 
2 17.1.2014....... 

我需要拿ID和名稱從表1和加入table1.id = table2.id並從表格2中只取前1行... 示例:

id Name   Date 
1  Example1 5.2.2014 
2  Example2 16.1.2014 

有可能嗎?

+0

哪個DBMS .. MSSQL或Mysql,oracle等? –

+0

也定義「頂行」。 SQL中的表格實際上並沒有任何固有的順序(索引基本上是優化細節),所以如果您不使用'ORDER BY'子句,則會以未定義的順序返回行。它看起來像你需要一個簡單的'MIN()'聚合,因爲一些答案正在顯示 - 你的表中的數據是否會支持這種簡單的查詢,還是我們需要更多的參與? –

回答

1

您可以使用row_number()過濾掉所有但最新一行每id

select * 
from (
     select row_number() over (partition by id order by Date desc) as rn 
     ,  * 
     from Table2 
     ) as t2 
join Table1 as t1 
on  t1.id = t2.id 
where t2.rn = 1 -- Only latest row 
+0

結果只是這樣:1 Example1 5.2.2014 ......我需要所有的結果: 1 Example1 5.2.2014 and 2 Example2 16.1.2014 – Kate

+0

哎呀,我忘了'partition by'子句。再試一次! – Andomar

+0

現在我有這個:1 Example1 5.2.2014 1 Example1 5.2.2014 1 Example1 5.2.2014 and 2 Example2 16.1.2014 2 Example2 16.1.2014 .......但是我只需要1個記錄來自table1的id。 .. – Kate

0

好了,一個簡單的嘗試將是

SELECT t1.*, 
     (SELECT TOP 1 t2.Date FROM Table2 t2 WHERE t2.ID = t1.ID t2.Date) t2Date 
FROM Table1 t1 

如果你使用SQL Server,你可以使用ROW_NUMBER

喜歡的東西

;WITH Vals AS (
      SELECT t1.ID, 
        t1.Name, 
        t2.Date, 
        ROW_NUMBER() OVER(PARTITION BY t1.ID ORDER BY t2.Date) RowID 
      FROm Table1 t1 LEFT JOIN 
        Table2 t2 ON t1.ID 
    ) 
    SELECT * 
    FROM Vals 
    WHERE RowID = 1 
+0

這沒關係? :SELECT t1。*, – Kate

+0

應該沒問題,但大多數人會推薦指定實際的列名,而不是使用'*' –

-1
Select t1.id, t1.name , MIN(t2.date) 
From table1 t1 
Inner Join table2 t2 
On t1.id=t2.id 
Group By t1.id, t1.name 
+0

請有人解釋這個解決方案的問題 –