SQL高级字符串比较

时间:2014-06-23 01:07:02

标签: sql sql-server

我正在努力从MSSQL数据库中获取一些非常具体的信息。我需要的所有信息都可通过以下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...                         |
+---------------------+---------------+--------------------------------------------------+

所以我想要的只是每个唯一描述字符串只有一个条目,唯一条目必须是最新收到的条目。

只有在SQL中才能实现这样的“高级”功能,还是必须使用python之类的其他语言进行后期处理?

如果可能,我想在纯SQL中做到这一点......

1 个答案:

答案 0 :(得分: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年问世 - 请使用它:)