获取最多两个条目查询

时间:2011-09-28 23:33:10

标签: sql sql-server-2005

查询:

select machinename, StatusCode, size
from machine where MachineID In( '33','22') and StatusCode = 166 
ORDER BY size DESC 

结果:

machinename  StatusCode  size
-----------  ----------  ----
test1        166         50
test1        166         25
test2        166         75
test2        166         48

要求:

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

由于

期望的结果:

machinename  StatusCode  size
-----------  ----------  ----
test1        166         50
test2        166         75

4 个答案:

答案 0 :(得分:4)

这样可行,但您无法通过starttime订购

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

答案 1 :(得分:3)

如果您想通过StartTime订购,则必须使用ROW_NUMBER,以便您可以选择启动时间字段:

SELECT machinename, StatusCode, size
FROM (
    SELECT
        machinename,
        StatusCode,
        StartTime
        size,
        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 StartTime DESC

但是如果你想按尺寸订购,那就更容易了:

SELECT machinename, StatusCode, MAX(size) AS size
FROM machine
WHERE MachineID IN ('33','22') AND StatusCode = 166 
GROUP BY MachineID
ORDER BY MAX(size) DESC

答案 2 :(得分:2)

使用窗口函数生成id以对键进行分区,然后按从大到小的顺序排序。这将为每个分区生成1-N,其中1将对应于ORDER BY中的最大值。然后我们过滤掉最大的那个。

; WITH MACHINES AS
(
select machinename, StatusCode, size
, ROW_NUMBER() OVER (PARTITION BY machinename ORDER BY size DESC) AS RN
from machine where MachineID In( '33','22') and StatusCode = 166 

)
SELECT
select machinename, StatusCode, size
FROM MACHINES M
WHERE M.rn = 1;

答案 3 :(得分:2)

select machinename, StatusCode, size
from machine a
where MachineID In( '33','22') and StatusCode = 166 
and size = (select max(size) 
from machine b
where MachineID In( '33','22') and StatusCode = 166 
and a.machinename = b.machinename)
ORDER BY StartTime DESC

HTH。