在T-SQL中选择两列摘要的最小差异

时间:2013-06-05 09:20:56

标签: sql-server tsql

我需要帮助构建一个查询,它返回Value +另一个值与同一个表之间的最小差异以及另一个给出结果的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 个答案:

答案 0 :(得分: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 with demo

答案 1 :(得分: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

答案 2 :(得分:0)

在Oracle中我会这样做:

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

想到SQL中类似的东西

答案 3 :(得分: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