删除SQL where子句中的+ - 值记录

时间:2015-02-16 07:33:21

标签: sql sql-server sql-server-2008-r2 sql-server-2012

我需要删除+ - 值记录意味着说

我只需要输出窗口中的蓝色两条记录。 希望清楚我到底想要什么。

User5   |  -15
User6   |  -10

I need only Blue colored two records.

2 个答案:

答案 0 :(得分:2)

我们的想法是获取第二列(在我的情况下是Val)被取消的行。您可以通过获取绝对值并指定按绝对值和值本身分组的行号来完成此操作。那些没有匹配的行号应该是结果。

WITH SampleData(UserID, Val) AS(
    SELECT 'User1', -10 UNION ALL
    SELECT 'User2', 10 UNION ALL
    SELECT 'User3', -15 UNION ALL
    SELECT 'User4', -10 UNION ALL
    SELECT 'User5', -15 UNION ALL
    SELECT 'User6', -10 UNION ALL
    SELECT 'User7', 10 UNION ALL
    SELECT 'User8', 15 
)
,Numbered AS(
    SELECT
        UserID,
        Val,
        BaseVal = ABS(Val),
        RN = ROW_NUMBER() OVER(PARTITION BY ABS(Val), Val ORDER BY UserId)
    FROM SampleData
)
SELECT 
    n1.UserID,
    n1.Val
FROM Numbered n1
LEFT JOIN Numbered n2 
    ON n2.BaseVal = n1.BaseVal
    AND n2.RN = n1.rn
    AND n2.UserID <> n1.UserID
WHERE n2.UserID IS NULL
ORDER BY n1.UserID

答案 1 :(得分:0)

似乎您想要总数不等于0的行?

    select 
      userName, 
      userValue 
    from 
      yourTable
    where 
      userName in (
      select userName from yourTable 
      group by userName 
      having sum (userValue) <> 0
    )