1

我需要帮助构建一个查询,该查询返回同一表中的值 + 另一个值与给出结果的另一个 ID 之间的最小差异(加上总和不能是值本身的总和)

桌子:

ID    Value
1     1        
2     2        
3     5        
4     -10      
5     -5
6     3
7     -15

预期结果:

ID    Value    MinDif   IDofTheOtherValue
1     1        3        2                   <-- MinDif = 1 + 2 (ID 1 + ID 2)
2     2        3        1                   <-- MinDif = 2 + 1 (ID 2 + ID 1)
3     5        0        5                   <-- MinDif = 5 + -5 (ID 3 + ID 5)
4     -10      -5       3                   <-- MinDif = -10 + 5 (ID 4 + ID 3)
5     -5       0        3                   <-- MinDif = -5 + 5 (ID 5 + ID 3)
6     3        -2       5                   <-- MinDif = 3 + -5 (ID 6 + ID 5)
7     -15      -10      3                   <-- MinDif = -15 + 5 (ID 7 + ID 3)

这是创建表的查询:

DECLARE @myTable TABLE(ID int, Value int)
INSERT INTO @myTable VALUES (1, 1), (2,2), (3, 5), (4, -10), (5, -5), (6, 3), (7, -15)

这是我尝试过的,但这会产生 SQL 错误(无法对包含聚合或子查询的表达式执行聚合函数。)

SELECT m.ID, MIN(ABS(m.Value + (SELECT m2.Value FROM @myTable m2)))
FROM @myTable m
4

4 回答 4

2

这给出了您需要的结果:

with diffRank as
(
  select ID = t1.ID
    , minDif = t1.value + t2.value
    , IDofTheOtherValue = t2.ID
    , diffRank = row_number() over (partition by t1.ID order by abs(t1.value + t2.value), t2.ID)
  from @myTable t1
    inner join @myTable t2 on t1.ID <> t2.ID
)
select ID
  , minDif
  , IDofTheOtherValue
from diffRank
where diffRank = 1
order by ID;

SQL Fiddle 与演示

于 2013-06-05T10:09:42.957 回答
1

我自己解决了这个问题。这是 Select 子句:

SELECT tab.ID, tab.Value, test.*    
FROM @myTable tab
OUTER APPLY 
(SELECT TOP 1 ID AS [AnotherID], [SUM]
    FROM
    (
        SELECT m.ID, m2.ID AS [ID2], m.Value + m2.Value AS [SUM]
        FROM @myTable m
        JOIN @myTable m2 ON m2.ID <> m.ID       
    ) apu WHERE ID2 = tab.ID ORDER BY ABS([SUM])) test
于 2013-06-05T10:01:47.227 回答
0

试试这个..它应该工作。

DECLARE @myTable TABLE(ID int, Value int)
INSERT INTO @myTable VALUES (1, 1), (2,2), (3, 5), (4, -10), (5, -5), (6, 3), (7, -15)

SELECT C.ID, C.Value
, C.Value + (SELECT TOP 1 E.Value FROM @myTable E WHERE C.AbsMinDif = ABS(C.Value + E.Value) ORDER BY E.ID) MinDif
, (SELECT TOP 1 F.ID FROM @myTable F WHERE C.AbsMinDif = ABS(C.Value + F.Value) ORDER BY F.ID) IDofTheOtherValue
FROM (

SELECT A.ID, MIN(A.Value) Value, MIN(ABS(A.Value + B.Value)) AbsMinDif   
FROM @myTable A
CROSS JOIN @myTable B 
WHERE A.ID <> B.ID
GROUP BY A.ID 

) C
于 2013-06-06T15:18:25.470 回答
0

在甲骨文我会做:

select x.id, (select min(abs(x.value + y.value)) from my_table y),
       (select first value (y.id) over (order by abs(x.value + y.value))
          from my_table y)
 from my_table x

想想 TSQL 中类似的东西

于 2013-06-05T10:20:30.633 回答