简体   繁体   中英

SQL Script Not Joining Results

I am having an issue getting this SQL Script to join the two tables together, I can execute it and it will show the results of the first portion (AccountID, AuditDate ..etc) but it will not join to the inner select statement.

I have verified by spot checking that there is data that matches in the database.

What portion did i mess up?

Select AccountID, AuditDate, SourceVersion
From Audit
Left join (
    Select A.PrinterAuditID, A.AuditID, A.SerialNr, A.PageCountTotal,a.PageCountColor, A.PageCountMono
    from  InvalidPrinterAudit A
    where A.DeviceID = 90757
) InvalidPrinterAudit on InvalidPrinterAudit.AuditID = Audit.AuditID

There's a couple of things happening here.

One : In order to have fields in your result set, they must be included in the SELECT portion of your query:

Select AccountID, AuditDate, SourceVersion, InvalidPrinterAudit.PrinterAuditID, InvalidPrinterAudit.AuditID, InvalidPrinterAudit.SerialNr, InvalidPrinterAudit.PageCountTotal,InvalidPrinterAudit.PageCountColor, InvalidPrinterAudit.PageCountMono
    From Audit
    Left join (
        Select A.PrinterAuditID, A.AuditID, A.SerialNr, A.PageCountTotal,a.PageCountColor, A.PageCountMono
        from  InvalidPrinterAudit A
        where A.DeviceID = 90757
    ) InvalidPrinterAudit on InvalidPrinterAudit.AuditID = Audit.AuditID

Two : You don't need to have a subquery here. Subqueries are great if you need to aggregate the results from a seperate table or something, but here you can just go with a LEFT OUTER JOIN and be done with it.

Select AccountID, AuditDate, SourceVersion, InvalidPrinterAudit.PrinterAuditID, InvalidPrinterAudit.AuditID, InvalidPrinterAudit.SerialNr, InvalidPrinterAudit.PageCountTotal,InvalidPrinterAudit.PageCountColor, InvalidPrinterAudit.PageCountMono
    From Audit
    Left OUTER JOIN InvalidPrinterAudit 
        ON InvalidPrinterAudit.AuditID = Audit.AuditID 
           AND InvalidPrinterAudit.DeviceID = 90757

This will apply that DeviceID = 90757 filter to your InvalidPrinterAudit before the join is applied, so you'll still get all of your Audit records, and then only the InvalidPrinterAudit records for that DeviceID that matches.

You are selecting less columns in the outer query than in the inner query.

If you want them to be returned in the resultset, include them in the outer:

Select AccountID, AuditDate, SourceVersion, PrinterAuditID, SerialNr
From Audit
Left join (
    Select A.PrinterAuditID, A.AuditID, A.SerialNr, A.PageCountTotal,a.PageCountColor, A.PageCountMono
    from  InvalidPrinterAudit A
    where A.DeviceID = 90757
) InvalidPrinterAudit on InvalidPrinterAudit.AuditID = Audit.AuditID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM