SQL Server查询,在1字段中获取具有不同值的记录,在其他字段中获取最大值

时间:2013-01-28 11:52:35

标签: sql sql-server excel ms-query

我有一些包含一些列的表:

WON   param      |  machine   |    inputdate     |  val
---|-------------|------------|------------------|--------|
18 | PAR.SPTDM.X1|    MM01    | 20/01/2013 12:43 |  2.5   |
18 | PAR.SPTDM.Y1|    MM01    | 20/01/2013 12:43 |  3,4   |
22 | PAR.SPTDM.X1|    MM01    | 22/01/2013 16:10 |  1.2   |
22 | PAR.SPTDM.Y1|    MM01    | 22/01/2013 16:10 |  1.7   |
33 | PAR.SPTDM.X1|    MM03    | 22/01/2013 16:13 |  2.34  |
33 | PAR.SPTDM.Y1|    MM03    | 22/01/2013 16:13 |  2,21  |
27 | PAR.LAS.PWR |    MM10    | 25/01/2013 08:14 |  100.5 |
14 | PAR.LAS.UV  |    MM10    | 18/01/2013 17:27 |  134.8 |
41 | PAR.LAS.UV  |    SLA4    | 27/01/2013 09:14 |  2,1   |
62 | PAR.LAS.UV  |    SLA5    | 27/01/2013 11:15 |  14.6  |

其中一些行被复制(由于我不知道的原因,它是管理系统的后端)。此外,value列是一个字符串,需要转换为数字。

数据库是只读的,我想根据以下几个条件将数据导入Excel表格:

  • 分组machineparam
  • 过滤param:仅'PAR.SPTDM.%'
  • 过滤machine:仅'MM%'
  • 用逗号忽略val,将其余部分转换为数字

使用以下查询时没有任何问题:

SELECT DISTINCT t1.param, t1.machine, cast(t1.val as float), t1.inputdate
FROM dbbackend t1
WHERE (t1.machine Like 'MM%')
    AND (t1.param Like 'PAR.SPTDM.%')
    AND (t1.val<>'') And (t1.val not Like '%,%')

现在我想只检索每台机器和每个参数(感兴趣的)的记录和最新的inputdate。首先我试过

SELECT DISTINCT t1.param, t1.machine, max(cast(t1.val as float)), max(t1.inputdate)
FROM dbbackend t1
WHERE (t1.machine Like 'MM%')
    AND (t1.param Like 'PAR.SPTDM.%')
    AND (t1.val<>'') And (t1.val not Like '%,%')
GROUP BY machine, param

但是这给了我val的不在数据集中的,正确的机器/参数/输入日期,但错误的val。

接下来尝试

SELECT DISTINCT t1.param, t1.machine, cast(t1.val as float), t1.inputdate
FROM dbbackend t1
WHERE t1.WON IN
    (
    SELECT latestrec.WON FROM (
        SELECT DISTINCT max(t2.WON), t2.param, t2.machine, max(t2.inputdate)
        FROM dbbackend t2
        WHERE (t2.machine Like 'MM%')
            AND (t2.param Like 'PAR.SPTDM.%')
            AND (t2.val<>'') And (t2.val not Like '%,%')
            GROUP BY machine, param
        ) as latestrec
    )

但这不起作用,MS Query告诉我

  

无法添加表'('。

所以有人可以告诉我为什么我在第一次调用时得到错误的值,为什么第二次调用不正常,或者什么是正确的方法?我还怀疑MS查询跳过那个嵌套的子查询:/

1 个答案:

答案 0 :(得分:3)

您可以使用CTE函数尝试此ROW_NUMBER

WITH x AS (SELECT t1.param, 
                t1.machine, 
                Cast(t1.val AS FLOAT) AS val, 
                t1.inputdate, 
                RN=Row_number() 
                     OVER( 
                       partition BY t1.machine, t1.param 
                       ORDER BY t1.inputdate DESC) 
         FROM   dbbackend t1 
         WHERE  ( t1.machine LIKE 'MM%' ) 
                AND ( t1.param LIKE 'PAR.SPTDM.%' ) 
                AND ( t1.val <> '' ) 
                AND ( t1.val NOT LIKE '%,%' )) 
SELECT param, 
       machine, 
       val, 
       inputdate 
FROM   x 
WHERE  rn = 1