以多对多关系获取两个字段中唯一的记录

时间:2012-06-01 09:50:31

标签: sql-server sql-server-2008

我正试图在多对多的表格中获得所有一对一的关系。

在下面的例子中,我想要返回的唯一记录是最后一个(3,3)

PaymentID InvoiceID
1          1
1          2
2          2
3          3

我最接近的是

Select * from Table where PaymentID in (
select PaymentID from Table t
inner join (
    select InvoiceId from Table 
    group by InvoiceId
    having count(InvoiceId) = 1
) inv on t.InvoiceId = inv.InvoiceId
group by PaymentId
having count(PaymentId) = 1
)

这将返回1和3

任何想法都非常感谢

感谢。

1 个答案:

答案 0 :(得分:4)

SELECT  *
FROM    (
        SELECT  *,
                COUNT(*) OVER (PARTITION BY paymentId) AS pcnt,
                COUNT(*) OVER (PARTITION BY invoiceId) AS icnt
        FROM    mytable
        ) q
WHERE   pcnt = 1
        AND icnt = 1