返回等价负数的行

时间:2018-11-12 22:32:56

标签: sql-server

我有一个带有几列的非标准化表。我想返回所有具有相同正值和相同值的负数的列。

示例:

ID  |  Value
-------------
1   |  10
1   | -10
3   |  15
3   |  15
4   | -1
5   |  4

当前输出:

ID | Values
-------------
1  |  10
1  | -10
3  |  15
3  |  15

所需的输出:

ID | Value
-------------
1 |  10
1 | -10

我制作了一个如下所示的windows函数,它将选择相同的绝对值,但是这包括具有正数的对。

select Count(*) Over (Partition By DVN, [Tran Date], [Reference Number],Description,Vendor, Abs([Maintenance Expense])) As cnt , * 
    From WorkTemp.dbo.Customer2700Combine
    Where [Maintenance Expense] Is Not Null
Order By 1 Desc,DVN, [Tran Date], [Reference Number],Description,Vendor, Abs([NonRental Total])

1 个答案:

答案 0 :(得分:0)

不确定您的要求是否是[ID],请查看您的示例,说明和所需的输出,这就是我的方法:

DROP TABLE IF EXISTS #sopg;

SELECT [ID],
       [VALUE]
INTO #sopg
FROM
(
    SELECT 1 AS ID,
           10 AS VALUE
    UNION
    SELECT 1 AS ID,
           -10 AS VALUE
    UNION
    SELECT 3 AS ID,
           15 AS VALUE
    UNION
    SELECT 3 AS ID,
           15 AS VALUE
    UNION
    SELECT 4 AS ID,
           -1 AS VALUE
    UNION
    SELECT 5 AS ID,
           4 AS VALUE
) x;

-- Assuming that one ID can only have maximum 2 rows (like your example above) and want this by ID

SELECT s.[ID],
       s.[VALUE]
FROM #sopg s
    INNER JOIN
        (
        SELECT ID,
               SUM(VALUE) SumZero
        FROM #sopg
        GROUP BY ID
        HAVING SUM(VALUE) = 0
    ) SumZero ON SumZero.ID = s.ID

  -- Another way, assuming that ID can have more than 2 rows and different values

DROP TABLE IF EXISTS #sopg2;

SELECT [ID],
       [VALUE]
INTO #sopg2
FROM
(
    SELECT 1 AS ID,
           10 AS VALUE
    UNION
    SELECT 1 AS ID,
           -10 AS VALUE
    UNION
        SELECT 1 AS ID,
           -9 AS VALUE
    UNION
    SELECT 3 AS ID,
           15 AS VALUE
    UNION
    SELECT 3 AS ID,
           15 AS VALUE
    UNION
    SELECT 4 AS ID,
           -1 AS VALUE
    UNION
    SELECT 5 AS ID,
           4 AS VALUE
) x

SELECT a.[ID],
       a.[VALUE]
FROM #sopg2 a
INNER JOIN #sopg b ON b.ID = a.ID AND a.VALUE = -b.VALUE