使用Union的SQL查询忽略行

时间:2017-09-18 15:17:02

标签: sql

我遇到了SQL查询的问题。当我尝试部分查询时,它对我来说很好。但是当我将它与Union结合使用时,它会跳过我在同一凭证中输入的值,但帐号是相同的。

例如,如果我在表中有两个具有相同帐号的条目,并尝试使用此查询获取它们:

SELECT 
    'DV-'+Convert(Varchar,VoucherNo) AS VoucherNo,
    DebitVouchersBody.AccountNo,
    AccountName,
    VoucherDate AS Date,
    DebitVouchersBody.Narration,
    Debit,
    0.00 AS Credit
FROM
    DebitVouchersBody
LEFT JOIN 
    ChartOfAccounts ON DebitVouchersBody.AccountNo = ChartOfAccounts.AccountNo
WHERE 
    DebitVouchersBody.AccountNo = '541' 

根据上面的查询,这对我来说很好,它会返回两个条目。

但是,当我使用union实现,如下面的查询所述,代码忽略了具有相同凭证编号和相同帐号的所有其他行。如果它在凭证中重复,则返回前一行帐号。无论帐号是否重复,我都希望获得所有行。

您能否建议我如何解决这个问题?

SELECT 
    'SI-'+Convert(Varchar,Sales.SaleID) AS VoucherNo,
    CustomerId AS AccountNo,
    AccountName, Date, Sales.Narration,
    InvoiceAmount-InvoiceDiscount AS Debit,
    PaidAmount AS Credit
FROM
    Sales
LEFT JOIN 
    ChartOfAccounts ON Sales.CustomerId = ChartOfAccounts.AccountNo
WHERE 
    CustomerId = '541'

UNION

SELECT 
    'PI-' + CONVERT(Varchar, Purchases.PurchaseId) AS VoucherNo,
    VendorId AS AccountNo,
    AccountName, Date, Purchases.Narration,
    AmountPaid AS Debit,
    InvoiceAmount AS Credit
FROM 
    Purchases
LEFT JOIN 
    ChartOfAccounts ON Purchases.VendorId = ChartOfAccounts.AccountNo
WHERE 
    VendorId = '541'

UNION

SELECT 
    'DV-' + CONVERT(Varchar, VoucherNo) AS VoucherNo,
    DebitVouchersBody.AccountNo,
    AccountName,
    VoucherDate AS Date,
    DebitVouchersBody.Narration,
    Debit,
    0.00 AS Credit
FROM
    DebitVouchersBody
LEFT JOIN 
    ChartOfAccounts ON DebitVouchersBody.AccountNo = ChartOfAccounts.AccountNo
WHERE 
    DebitVouchersBody.AccountNo = '541'

UNION

SELECT 
    'CV-' + CONVERT(Varchar,VoucherNo) AS VoucherNo,
    CreditVouchersBody.AccountNo,
    AccountName,
    VoucherDate AS Date,
    CreditVouchersBody.Narration,
    0.00 AS Debit,
    Credit
FROM
    CreditVouchersBody
LEFT JOIN 
    ChartOfAccounts ON CreditVouchersBody.AccountNo = ChartOfAccounts.AccountNo
WHERE 
    CreditVouchersBody.AccountNo = '541'

UNION

SELECT 
    'JV-' + CONVERT(Varchar, VoucherNo) AS VoucherNo,
    JournalVouchersBody.AccountNo,
    AccountName,
    VoucherDate AS Date,
    JournalVouchersBody.Narration,
    Debit,
    Credit
FROM
    JournalVouchersBody
LEFT JOIN 
    ChartOfAccounts ON JournalVouchersBody.AccountNo = ChartOfAccounts.AccountNo
WHERE 
    JournalVouchersBody.AccountNo = '541'

UNION

SELECT 
    NULL AS VoucherNo,
    NULL AS AccountNo,
    NULL AS Name,
    NULL AS Date,
    'Opening Balance' AS Narration,
    OpeningDebit AS Debit,
    OpeningCredit AS Crdit
FROM
    ChartOfAccounts
WHERE 
    AccountNo = '541'
ORDER BY 
    Date, VoucherNo

0 个答案:

没有答案