------------------------------------
X Y
------------------------------------
10 20
10 5
10 9
50 40
50 30
100 70
100 100
将1,2,3行视为A组 B组为4,5行 和6,7行作为C组
我想为一个组只获得一行,并且该行应该取决于 X,Y列值。
Y列的值最接近x
预期结果
------------------------------------
X Y
------------------------------------
10 9
50 40
100 100
答案 0 :(得分:5)
您可以使用条件聚合执行此操作:
select x, max(case when y <= x then y end) as y
from table t
group by x;
答案 1 :(得分:1)
替代解决方案
DECLARE @tb TABLE (
X float , Y float
)
INSERT INTO @tb (X,Y) values
(10, 20),
(10, 5),
(10, 9),
(50, 40),
(50, 30),
(100, 70),
(100, 100);
select a.* from (
select row_number() over( partition by X order by abs(X-Y) asc ) as rn, X, Y
from @tb
) a where a.rn = 1;
答案 2 :(得分:1)
DECLARE @tb TABLE (
X float , Y float
)
INSERT INTO @tb (X,Y) values
(10, 20),
(10, 5),
(10, 9),
(50, 40),
(50, 30),
(100, 70),
(100, 100);
; WITH CTE AS
(
Select t.X,t.Y,RN from (Select tt.X,tt.Y,ROW_NUMBER()OVER(PARTITION BY tt.X ORDER BY tt.Y DESC)RN from @tb tt )t
)
Select DISTINCT C.X,MAX(CASE WHEN C.Y <= C.X THEN C.Y END)AS Y FROM CTE C
GROUP BY C.X