排除键匹配但在不同行上的行

时间:2019-01-25 18:49:31

标签: sql sql-server database

我正在寻找提供所提供方案中结果集的最佳方法。我的cust3列未标识indvid2列中的重复值。我要寻找的最终结果是排除key1和key2匹配的行(ids:1、2、6和7),然后对acctids匹配的行求和。如果有更好的编码方式,我欢迎大家建议。谢谢!

WITH T10 as (
SELECT acctid,invid,(
case
when invid like '%-R' then left (InvID,LEN(invid) -2) else InvID
     END) as InvID2
FROM table x 
    GROUP BY acctID,invID 
    ),


T11 as (
SELECT acctid, Invid2, COUNT(InvID2) as cust3
FROM T10
    GROUP BY InvID2,acctid
    HAVING 
    COUNT (InvID2) > 1
    )

select DISTINCT
a.acctid,
a.name,
b.invid,
C.invid2,
D.cust3,
b.amt,
b.key1,
b.key2

from table a
inner join table b (nolock) on a.acctid = b.acctid
inner join T10 C (nolock) on b.invid = c.invid
inner join T11 D (nolock) on C.invid2 = D.invid2

结果集

id  acctID  name    invid   invid2  Cust3   amt     key1    key2
1   123    James    101      101    2      $500     NULL    6789
2   123    james    101-R    101    2     ($500)    6789    NULL
3   123    James    102      102    2      $350     NULL    NULL
4   123    James    103      103    2      $200     NULL    NULL
5   246     Tony    98-R      98    2     ($750)    7423    NULL
6   432    David    45        45    2      $100     NULL    9634
7   432    David    45-R      45    2     ($100)    9634    NULL
8   359     Stan    39-R      39    2      ($50)    6157    NULL
9   753   George    95        95    2      $365     NULL    NULL
10  753   George    108      108    2      $100     NULL    NULL

所需结果集

id  acctID  name    invid   invid2  Cust3   amt     key1    key2
1   123    James    101      101    2      $500     NULL    6789
2   123    james    101-R    101    2     ($500)    6789    NULL
3   123    James    102      102    1      $350     NULL    NULL
4   123    James    103      103    1      $200     NULL    NULL
5   246     Tony    98-R      98    1     ($750)    7423    NULL
6   432    David    45        45    2      $100     NULL    9634
7   432    David    45-R      45    2     ($100)    9634    NULL
8   359     Stan    39-R      39    1      ($50)    6157    NULL
9   753    George   95        95    1      $365     NULL    NULL
10  753    George   108      108    1      $100     NULL    NULL

然后按acctid求和

id  acctid  name    amt                 
1   123    James    $550                    
2   246     Tony    ($750)                  
3   359     Stan    ($50)                   
4   753    George   $465    

1 个答案:

答案 0 :(得分:0)

类似的东西:

;WITH Keys as (
    SELECT Key1.acctID, [Key] = Key1.Key1
    FROM YourTable as Key1
    INNER JOIN YourTable as Key2
        ON Key1.Key1 = Key2.Key2 and Key1.acctID = Key2.acctID
)
SELECT t.acctID, t.name, amt = SUM(t.amt)
FROM YourTable as t
LEFT JOIN Keys as k
    ON t.acctID = k.acctID and (t.Key1 = [Key] or t.Key2 = [Key])
WHERE k.acctID is Null
GROUP BY t.acctID, t.name