SQL Join返回表中的所有行

时间:2014-03-13 13:16:32

标签: sql sql-server

我希望从表中获取一个帐户名,但它返回表中的两行而不是匹配的行。这是名为LEDGERTRANS的表:

Account    Date           Voucher
402000  2014-01-14    CM-00011026   
554500  2014-01-14    CM-00011026

这是一个名为LEDGERTABLE的表,它将根据此表帐号匹配帐户。因此,我们获得一个凭证号码,然后是帐号,然后将其与表格相匹配以获取帐户名称。问题是这会从表中带回两个账号描述。这是SQL

    SELECT DISTINCT
    dbo.CUSTTABLE.NAME AS 'Customer',
    dbo.CUSTINVOICEJOUR.INVOICEACCOUNT AS 'Acct #',
    dbo.CUSTINVOICEJOUR.SALESID AS 'Sales Order',
    dbo.CUSTINVOICEJOUR.INVOICEDATE AS 'Date',
    dbo.CUSTINVOICEJOUR.INVOICEID AS 'Invoice',
    (INVOICEAMOUNT - SALESBALANCE) AS 'Inv Amt',
    'Misc Charge' AS ITEMID,
    'Misc. Charge' AS 'Reason',
    [DESCRIPTION] AS 'Division',
    CREATEDBY
    ,LEDGERTABLE.ACCOUNTNUM as 'Account Number'
FROM
    dbo.CUSTINVOICEJOUR INNER JOIN
    dbo.CUSTINVOICETRANS ON dbo.CUSTINVOICEJOUR.INVOICEID = dbo.CUSTINVOICETRANS.INVOICEID INNER JOIN 
    dbo.CUSTTABLE ON ACCOUNTNUM = dbo.CUSTINVOICEJOUR.INVOICEACCOUNT INNER JOIN 
    dbo.DIMENSIONS ON NUM = dbo.CUSTINVOICEJOUR.DIMENSION2_
    JOIN LEDGERTRANS ON LEDGERTRANS.VOUCHER = CUSTINVOICEJOUR.INVOICEID
    inner JOIN LedgerTable ON LedgerTable.ACCOUNTNUM = Ledgertrans.ACCOUNTNUM
WHERE
    dbo.CUSTINVOICEJOUR.INVOICEID LIKE 'CM-00%'
    AND
    dbo.CUSTINVOICEJOUR.INVOICEDATE BETWEEN @start AND @end
    AND
    dbo.CUSTINVOICEJOUR.DIMENSION2_ IN (@division)
    AND
    INVOICEAMOUNT <> SALESBALANCE
    AND
    CREATEDBY IN (@createdBy)
    AND 
    LEDGERTRANS.CREDITING='0'

这有效地为每个项目带回2个条目。我怎样才能摆脱这一额外的行?

C3 Ingenuity    110051  SO-00670938 CM-00011026 -33.750000000000    Misc Charge 402000
C3 Ingenuity    110051  SO-00670938 CM-00011026 -33.750000000000    Misc Charge 554500

甚至:

Select LEDGERTABLE.ACCOUNTNUM from LedgerTable JOIN Ledgertrans ON LedgerTable.ACCOUNTNUM = Ledgertrans.ACCOUNTNUM Where LEDGERTRANS.VOUCHER = CUSTINVOICEJOUR.INVOICEID

返回两个结果

1 个答案:

答案 0 :(得分:0)

区别在于最后一栏(如果我理解正确,则为LEDGERTABLE.ACCOUNTNUM。)

您可以从查询中排除表/列,或从剩余列中排除GROUP /列,从现有帐号中删除MIN / MAX