我有以下查询
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
我怎样才能在最小值和最大值之间检索值,就像我为min和max做的那样?
实施例
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
答案 0 :(得分: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在评论中指出),这个技巧才有效。