2

我有以下查询

SELECT  Cod ,
        MIN(Id) AS id_Min,
        MAX(Id) AS id_Max,
        -- retrieve value in the middle,
        COUNT(*) AS Tot

FROM    Table a ( NOLOCK )        
GROUP BY Cod
HAVING  COUNT(*)=3

我如何检索最小值和最大值之间的值,就像我对最小值和最大值所做的那样?

例子

Cod      |  Id

Stack       10
Stack       15
Stack       11
Overflow    100
Overflow    120
Overflow    15

所需输出

Cod         | Min   | Value_In_The_Middle  |    Max

Stack         10          11                    15
Overflow      15          100                   120
4

1 回答 1

4

我还没有测试过这个,但我认为这会工作

SELECT  Cod ,
        MIN(Id) AS id__Min,
        MAX(Id) AS id_Max,
        SUM(ID)-MAX(Id)-MIN(Id) as id_Middle,
        COUNT(*) AS Tot
FROM    Table a ( NOLOCK )        
GROUP BY Cod
HAVING  COUNT(*)=3

这个技巧只有在你有 3 个值并且 SUM() 没有溢出时才有效(就像Bogdan Sahlean在评论中指出的那样)。

于 2012-04-18T09:59:08.893 回答