查询从多行获取一个条目

时间:2011-09-29 19:47:49

标签: sql sql-server database

查询:

select machinename, StatusCode, max(size) as size, statusID
from machine where MachineID In( '33','22') and StatusCode = 166 
group by machinename, StatusCode, statusID
order by max(size) DESC

结果:

   machinename  StatusCode  size statusID
    -----------  ----------  ---- --------
    test1        166         50       1
    test1        166         25       2
    test2        166         75       3
    test2        166         48       4

要求:

我需要为每台机器只显示一个条目。 我必须通过获取两个条目之间的最大大小值来完成此操作,如上所示。 对于test1我有两个尺寸50和25我必须显示有50的行而忽略有25的行。

由于

期望的结果:

 machinename  StatusCode  size statusID
    -----------  ----------  ---- --------
    test1        166         50       1  
    test2        166         75       3 

2 个答案:

答案 0 :(得分:3)

SELECT machinename, StatusCode, size, statusID
FROM (
    SELECT
        machinename,
        StatusCode,
        size,
        statusID,
        ROW_NUMBER() OVER (PARTITION BY MachineID ORDER BY size DESC) AS rn
    FROM machine
    WHERE MachineID IN ('33','22')
    AND StatusCode = 166 
) T1
WHERE rn = 1
ORDER BY size DESC 

答案 1 :(得分:2)

“旧”SQL Server的三种解决方案 s

SELECT  *
FROM    TestData a
WHERE   a.Size >= ALL(SELECT b.Size FROM TestData b WHERE b.MachineName=a.MachineName);

SELECT  *
FROM    TestData a
WHERE   a.Size = (SELECT MAX(b.Size) FROM TestData b WHERE b.MachineName=a.MachineName);

SELECT  a.*
FROM    TestData a
JOIN    (SELECT MachineName, MAX(Size) MaxSize FROM TestData GROUP BY MachineName) b 
ON      a.MachineName=b.MachineName 
AND     a.Size=b.MaxSize;

结果:

MachineName StatusCode  Size        StatusID
----------- ----------- ----------- -----------
test2       166         75          3
test1       166         50          1

警告:如果有很多行具有相同的机器最大值,则所有这些查询都会显示这些行。