SQL 服务器查询以在单个 table 中查找没有父项和子项的行

SQL Server query to find rows that have no parent and child in a single table

我有这个table:

CREATE TABLE dbo.Invoices 
(
    [InvoiceCode] varchar(20), 
    [ParentInvoiceCode] varchar(20),
    [InvoiceDate] date 
)

INSERT INTO dbo.Invoices
VALUES
( 'INV-001', 'INV-001', N'2015-01-01 00:00:00.000' ),
( 'INV-002', 'INV-001', N'2015-01-01 00:00:00.000' ),
( 'INV-003', 'INV-001', N'2015-01-01 00:00:00.000' ),
( 'INV-004', 'INV-004', N'2015-01-01 00:00:00.000' ),
( 'INV-005', 'INV-005', N'2015-01-01 00:00:00.000' ),
( 'INV-006', 'INV-006', N'2015-01-01 00:00:00.000' ),
( 'INV-007', 'INV-007', N'2015-01-01 00:00:00.000' ),
( 'INV-008', 'INV-007', N'2015-01-01 00:00:00.000' ),
( 'INV-009', 'INV-007', N'2015-01-01 00:00:00.000' ),
( 'INV-010', 'INV-007', N'2015-01-01 00:00:00.000' )

如您所见,值 4、5、6 没有父行或子行。我可以使用什么查询来找到这些?

所以这只是一个简单的 not-exists 查询:

查找 codeparentcode 相同但不存在不同 parentcode 的所有行。

另请注意,您不能拥有超过 999 个发票代码并且仍然可以订购它们,代码和父代码应为 integer 列。否则当你想添加 INV-1000 时,它会被认为 less 而不是 INV-999 因为这些是 strings!

select * 
from invoices i
where i.ParentInvoiceCode = i.InvoiceCode
    and not exists (
        select * from invoices i2
        where i2.ParentInvoiceCode = i.InvoiceCode 
            and i2.InvoiceCode != i2.ParentInvoiceCode
    )