消除具有相反值的行

时间:2016-11-18 16:16:36

标签: sql sql-server tsql

我想消除具有相反值的行 我的表格中有以下行

id     value1  value2  value3
----   ------  ------  -------
10     -1        -20     -48.5
10      1         20      48.5
10     -1        -30     -26.2
10      1         30      26.2
10      1         27      30.5

我想得到的是

id     value1  value2  value3
----   ------  ------  -------
10      1         27      30.5

任何建议都将不胜感激。

3 个答案:

答案 0 :(得分:0)

我正在回复正数。然后我将所有字段分组,只返回单行字段。您可以在选择中使用ofstreamMIN。两者都会返回正确的结果。

MAX

结果:

DECLARE @Tbl TABLE (id INT, value1 INT, value2 INT, value3 FLOAT)

INSERT INTO @Tbl        
VALUES 
(10,     -1,        -20,     -48.5),
(10,      1,         20,      48.5),
(10,     -1,        -30,     -26.2),
(10,      1,         30,      26.2),
(10,      1,         27,      30.5)


SELECT
    T.id ,
    MIN(T.value1) ,
    MIN(T.value2),
    MIN(T.value3)
FROM
    @Tbl T
GROUP BY
    T.id ,
    ABS(T.value1) ,
    ABS(T.value2),
    ABS(T.value3) HAVING COUNT(1) = 1

我建议你在更大的数据上进行测试。您可能遇到性能问题。

答案 1 :(得分:0)

这个怎么样:

DECLARE @T TABLE (
    id INT,
    value1 INT,
    value2 INT,
    value3 DECIMAL(9,2)
)

INSERT @T VALUES
(10, -1, -20, -48.5),
(10, 1, 20, 48.5),
(10, 1, -20, -48.5),
(10, -1, 20, 48.5),
(10, -1, -30, -26.2),
(10, 1, 30, 26.2),
(10, 1, 27, 30.5)

SELECT A.* FROM @T A
LEFT JOIN @T B ON
    B.id = A.id
    AND B.value1 = -A.value1
    AND B.value2 = -A.value2
    AND B.value3 = -A.value3
WHERE B.id IS NULL

答案 2 :(得分:0)

/*
Compare the Table to itself to look for opposite values.
You can achieve that by multiplying the value of the second table by -1, looking for the opposite.
Since you did not specified if all or some of the values have to be opposites, i assumed they all must be opposites, and that's why I use AND in the JOIN.
If the condition is met just by any value, then change the AND by OR in the JOIN.
*/

DECLARE     @MyTable    TABLE   (id int, value1 int, value2 int, value3 numeric(5,1))
INSERT INTO @MyTable    VALUES
            (10, -1, -20, -48.5)
        ,   (10,  1,  20,  48.5)
        ,   (10, -1, -30, -26.2)
        ,   (10,  1,  30,  26.2)
        ,   (10,  1,  27,  30.5)
;

SELECT          T1.*

FROM            @MyTable    T1
    LEFT JOIN   @MyTable    T2  ON  (T2.value1 = -1 * T1.value1)
                                AND (T2.value2 = -1 * T1.value2)
                                AND (T2.value3 = -1 * T1.value3)
WHERE   T2.id   IS NULL