2016-05-13 55 views
1

我想創建一個SQL查詢,我只能查看最新的貨件。目前我得到以下結果。用於獲取最新數據的SQL查詢

item date  licence plate number 
1  13.5.2016 abc-123 
2  13.5.2016 abc-123 
3  10.5.2016 xyz-567 
1  20.4.2016 abc-123 
2  20.4.2016 abc-123 
6  10.5.2016 xyz-567 

但是我想只根據車牌號獲得最新的貨件。想要的輸出會看起來像

item date  licence plate number 
1  13.5.2016 abc-123 
2  13.5.2016 abc-123 
3  10.5.2016 xyz-567 
+1

你使用的是什麼dbms? –

+0

定義「最新」,然後我們可以幫助你。項目3包括什麼,但項目6被排除? – Andreas

+0

您正在使用哪些DBMS? –

回答

3

您可以使用下面的查詢:

SELECT t1.* 
FROM mytable AS t1 
JOIN (
    SELECT item, MAX("date") AS "date" 
    FROM mytable 
    GROUP BY item 
) AS t2 ON t1.item = t2.item AND t1."date" = t2."date" 

查詢使用派生表,選擇每item的最後日期。使用這個派生表,我們可以選擇與這個日期相對應的記錄。

0

也許這會有所幫助:

SELECT TOP 10 --change 10 to any desired number to be viewed 
* 
FROM YourDatabaseName 
ORDER BY Date DESC 
+0

不是OP要求的。 (並且產品特定的答案是不帶dbms標籤的問題。) – jarlh

0

你必須先找到我們每個車牌號碼的最大日再加入表。

您可以使用下面的查詢。

select t2."item",t1."date",t1."licence plate number" from (
(select max("date") as date, "licence plate number" from Table_1 group by 
"licence plate number")) t1 
left join Table_1 t2 
on (t1."date" = t2."date" and t1."licence plate number" = t2."licence plate number") 

此查詢的輸出將是。

1  2016-05-13  abc-123 
2  2016-05-13  abc-123 
3  2016-05-10  xyz-567 
6  2016-05-10  xyz-567 
+0

請注意,分隔標識符的方括號是特定於產品的,並且問題沒有標記dbms。 ANSI SQL有雙引號,例如' 「項目」'。 (MS SQL Server實際上支持這兩個版本。) – jarlh

+0

感謝bro .. @jarlh –

1

以下是一個廣泛的DBMS支持的標準SQL:

select item, date, licence_plate_number 
from (
    select item, date, licence_plate_number, 
      row_number() over (partition by licence_plate_number order by date desc as rn) 
    from the_table 
) t 
where rn = 1 
order by item; 

使用窗函數通常快於自與集料加入。