2014-06-23 57 views
0

我正在從MSSQL數據庫中獲取一些非常具體的信息。我需要的所有信息通過SQL命令可用:字符串的SQL高級比較

SELECT 
receivedate, 
swp.firmwarelevel AS 'Firmwarelevel', 
pa.description AS 'Description' 
FROM tbl_swapgroup_parts swp, tbl_parts pa, tbl_part_type pt, tbl_swapgroups sw, tbl_workorders wo 
WHERE custom7 = 'somemodel' 
AND swp.swapgroup_id IN (18,25) 
AND sw.id = swp.swapgroup_id 
AND pa.id = swp.part_id 
AND pt.id = pa.parttype_id 
AND wo.part_id = pa.id' 

現在這個返回它看起來像這樣的列表,修整爲理智僅有4項...

+---------------------+---------------+--------------------------------------------------+ 
|  receivedate  | Firmwarelevel |     Description     | 
+---------------------+---------------+--------------------------------------------------+ 
| 2013-08-29 12:10:28 |  YN07  |   Description 1...       | 
| 2013-08-29 12:10:28 |  YN07  |   Description 2...       | 
| 2014-01-13 13:12:55 |  YN07  |   Description 1...       | 
| 2014-01-13 13:12:55 |  YN07  |   Description 2...       | 
+---------------------+---------------+--------------------------------------------------+ 

所以我對於每個唯一描述字符串,實際上只需要1個條目,唯一條目必須是具有最新收到的條目。

這樣的'高級'的東西可能只有在SQL中,或者我必須後續處理一些其他語言,如Python?

如果可能的話我想要一份做純SQL ...

+1

你試圖按receivedate和秩序? –

+0

謝謝我會嘗試。我看到的第一個SQL是2個小時之前,所以我有很多東西要學 – RG337

回答

2

是的,你可以在SQL做到這一點。例如,row_number()

SELECT * FROM (
    SELECT 
    receivedate, 
    swp.firmwarelevel AS 'Firmwarelevel', 
    pa.description AS 'Description', 
    row_number() over (partition by Description order by receivedate desc) rn 
FROM tbl_swapgroup_parts swp, 
     tbl_parts pa, 
     tbl_part_type pt, 
     tbl_swapgroups sw, 
     tbl_workorders wo 
WHERE custom7 = 'somemodel' 
    AND swp.swapgroup_id IN (18,25) 
    AND sw.id = swp.swapgroup_id 
    AND pa.id = swp.part_id 
    AND pt.id = pa.parttype_id 
    AND wo.part_id = pa.id 
) x 
where x.rn=1 

此外,ANSI JOIN syntax在1992年就出來了 - 請receivedate遞減使用它:)