Solved

How To - SubQuery to replace MAX DISTINCT

Posted on 2013-11-18
6
404 Views
Last Modified: 2013-11-25
I am receiving "The multipart identifier xxx could not be bound" in a SELECT query using MAX DISTINCT on a column, MAX(DISTINCT Floyd.dbo.SOPInvoiceCreditLine.DespatchReceiptNos) AS DespatchNumber

The main query is part of a stored procedure.

The table SOPInvoiceCreditLine will have a number of matching rows where at least one row will have a value in the column DespatchNumber, the other rows will have an 'empty' DespatchNumber. I need to return one non-empty instance only of DespatchNumber in the main query. I suspect a subquery may be needed, however I always find these a 'dark art'

SELECT        TOP (100) PERCENT Floyd.dbo.SLCustomerAccount.CustomerAccountNumber, Floyd.dbo.SOPInvCredDelAddress.PostalName, 
                         Floyd.dbo.SOPInvCredDelAddress.AddressLine1 AS DeliveryAddress1, Floyd.dbo.SOPInvCredDelAddress.PostCode AS DeliveryPostCode, 
                         CASE WHEN Floyd.dbo.SOPOrderReturn.CustomerDocumentNo = '' THEN 'No Order No.' ELSE Floyd.dbo.SOPOrderReturn.CustomerDocumentNo END AS CustomerOrder,
                          MAX(DISTINCT Floyd.dbo.SOPInvoiceCreditLine.DespatchReceiptNos) AS DespatchNumber, Floyd.dbo.SOPOrderReturn.DocumentNo AS FloydReference, 
                         Floyd.dbo.SOPInvoiceCredit.DocumentNo AS FloydDocumentNumber, Floyd.dbo.SOPInvoiceCredit.DocumentDate AS FloydDocumentDate, 
                         Floyd.dbo.SOPInvoiceCredit.InvoicedNetValue, Floyd.dbo.SOPInvoiceCredit.InvoicedTaxValue, Floyd.dbo.SOPInvoiceCredit.InvoicedGrossValue
FROM            Floyd.dbo.SLCustomerAccount INNER JOIN
                         Floyd.dbo.SOPInvoiceCredit ON Floyd.dbo.SLCustomerAccount.SLCustomerAccountID = Floyd.dbo.SOPInvoiceCredit.CustomerID INNER JOIN
                         Floyd.dbo.SOPInvoiceCreditLine ON Floyd.dbo.SOPInvoiceCredit.SOPInvoiceCreditID = Floyd.dbo.SOPInvoiceCreditLine.SOPInvoiceCreditID INNER JOIN
                         Floyd.dbo.SOPInvCredDelAddress ON Floyd.dbo.SOPInvoiceCredit.SOPInvoiceCreditID = Floyd.dbo.SOPInvCredDelAddress.SOPInvoiceCreditID INNER JOIN
                         Floyd.dbo.SOPOrderReturn ON Floyd.dbo.SOPInvoiceCredit.SecondReference = Floyd.dbo.SOPOrderReturn.DocumentNo
WHERE        (Floyd.dbo.SOPInvoiceCredit.SOPInvoiceCreditTypeID = 0) AND (Floyd.dbo.SOPInvoiceCredit.DocumentDate BETWEEN CONVERT(DATETIME, '2013-10-01 00:00:00', 
                         102) AND CONVERT(DATETIME, '2013-10-31 00:00:00', 102))
GROUP BY Floyd.dbo.SLCustomerAccount.CustomerAccountNumber, Floyd.dbo.SOPOrderReturn.DocumentNo, Floyd.dbo.SOPInvoiceCredit.DocumentDate, 
                         Floyd.dbo.SOPInvoiceCredit.DocumentNo, 
                         CASE WHEN Floyd.dbo.SOPOrderReturn.CustomerDocumentNo = '' THEN 'No Order No.' ELSE Floyd.dbo.SOPOrderReturn.CustomerDocumentNo END, 
                         Floyd.dbo.SOPInvoiceCredit.InvoicedNetValue, Floyd.dbo.SOPInvoiceCredit.InvoicedTaxValue, Floyd.dbo.SOPInvoiceCredit.InvoicedGrossValue, 
                         Floyd.dbo.SOPInvCredDelAddress.PostalName, Floyd.dbo.SOPInvCredDelAddress.AddressLine1, Floyd.dbo.SOPInvCredDelAddress.PostCode
HAVING        (Floyd.dbo.SLCustomerAccount.CustomerAccountNumber = '843') AND (MAX(DISTINCT Floyd.dbo.SOPInvoiceCreditLine.DespatchReceiptNos) <> '')

Open in new window

0
Comment
Question by:TeDeSm
6 Comments
 

Author Comment

by:TeDeSm
ID: 39656483
I managed to find the correct syntax for the subquery, it's OK if only one value is returned for each row in the main query.
(SELECT DISTINCT TOP (100) PERCENT DespatchReceiptNos
                               FROM            Floyd.dbo.SOPInvoiceCreditLine AS SOPIC
                               WHERE        (DespatchReceiptNos <> '') AND (Floyd.dbo.SOPInvoiceCredit.SOPInvoiceCreditID = SOPInvoiceCreditID)) AS DespatchNumber,

Open in new window

0
 
LVL 39

Expert Comment

by:Aaron Tomosky
ID: 39658564
On my phone so I'm not gonna type the whole thing. Basically you use
Select top 1 columnname
From blah
Where whatever = something
Order by othercolumnname
0
 
LVL 15

Accepted Solution

by:
dbbishop earned 250 total points
ID: 39659483
Not even sure why you would use MAX(DISTINCT columnname). I hope the query analyzer strips the DISTINCT out of the equation.
What is the difference between MAX() function if you have 1,2,3,4,5 and 1,1,2,2,3,3,3,4,4,4,5,5,5,5. MAX() is still 5.
0
NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

 

Author Comment

by:TeDeSm
ID: 39659573
The data returned from the table will either have the same DespatchReceiptNos value, or empty for each row with the foreign key of SOPInvoiceCreditID. So MAX should return a unique DespatchReceiptNos  for each SOPInvoiceCreditID.

I did have to tackle this problem from a different angle as all was OK in a simple view, but returned an error in a stored procedure when returning data from live and archived tables, unioned together. I have a working stored procedure now but it's somewhat too big to publish here but basically I use a cte to get the unique DespatchReceiptNos with its SOPInvoiceCreditID key then used the output in my main cte query linked on SOPInvoiceCreditID.
0
 
LVL 40

Assisted Solution

by:Sharath
Sharath earned 250 total points
ID: 39670750
MAX(DISTINCT) is not required as suggested by dbbishop. I moved the condition "Floyd.dbo.SOPInvoiceCreditLine.DespatchReceiptNos <> '' " to WHERE clause from HAVING clause.
Check if you are still getting multiple records with this. Do you have a PK columns for each record? If so, you can re-write this query with ROW_NUMBER removing the GROUP BY clause.
SELECT Floyd.dbo.SLCustomerAccount.CustomerAccountNumber, 
       Floyd.dbo.SOPInvCredDelAddress.PostalName, 
       Floyd.dbo.SOPInvCredDelAddress.AddressLine1            AS DeliveryAddress1, 
       Floyd.dbo.SOPInvCredDelAddress.PostCode                AS DeliveryPostCode, 
       CASE 
         WHEN Floyd.dbo.SOPOrderReturn.CustomerDocumentNo = '' THEN 'No Order No.' 
         ELSE Floyd.dbo.SOPOrderReturn.CustomerDocumentNo 
       END                                                    AS CustomerOrder, 
       MAX(Floyd.dbo.SOPInvoiceCreditLine.DespatchReceiptNos) AS DespatchNumber, 
       Floyd.dbo.SOPOrderReturn.DocumentNo                    AS FloydReference, 
       Floyd.dbo.SOPInvoiceCredit.DocumentNo                  AS FloydDocumentNumber, 
       Floyd.dbo.SOPInvoiceCredit.DocumentDate                AS FloydDocumentDate, 
       Floyd.dbo.SOPInvoiceCredit.InvoicedNetValue, 
       Floyd.dbo.SOPInvoiceCredit.InvoicedTaxValue, 
       Floyd.dbo.SOPInvoiceCredit.InvoicedGrossValue 
  FROM Floyd.dbo.SLCustomerAccount 
       INNER JOIN Floyd.dbo.SOPInvoiceCredit 
               ON Floyd.dbo.SLCustomerAccount.SLCustomerAccountID = Floyd.dbo.SOPInvoiceCredit.CustomerID
       INNER JOIN Floyd.dbo.SOPInvoiceCreditLine 
               ON Floyd.dbo.SOPInvoiceCredit.SOPInvoiceCreditID = Floyd.dbo.SOPInvoiceCreditLine.SOPInvoiceCreditID
       INNER JOIN Floyd.dbo.SOPInvCredDelAddress 
               ON Floyd.dbo.SOPInvoiceCredit.SOPInvoiceCreditID = Floyd.dbo.SOPInvCredDelAddress.SOPInvoiceCreditID
       INNER JOIN Floyd.dbo.SOPOrderReturn 
               ON Floyd.dbo.SOPInvoiceCredit.SecondReference = Floyd.dbo.SOPOrderReturn.DocumentNo
 WHERE ( Floyd.dbo.SOPInvoiceCredit.SOPInvoiceCreditTypeID = 0 ) 
   AND ( Floyd.dbo.SOPInvoiceCredit.DocumentDate BETWEEN CONVERT(DATETIME, '2013-10-01 00:00:00', 102) AND CONVERT(DATETIME, '2013-10-31 00:00:00', 102) ) 
   AND Floyd.dbo.SOPInvoiceCreditLine.DespatchReceiptNos <> ''
   AND Floyd.dbo.SLCustomerAccount.CustomerAccountNumber = '843'    
 GROUP BY Floyd.dbo.SLCustomerAccount.CustomerAccountNumber, 
          Floyd.dbo.SOPOrderReturn.DocumentNo, 
          Floyd.dbo.SOPInvoiceCredit.DocumentDate, 
          Floyd.dbo.SOPInvoiceCredit.DocumentNo, 
          CASE 
            WHEN Floyd.dbo.SOPOrderReturn.CustomerDocumentNo = '' THEN 'No Order No.' 
            ELSE Floyd.dbo.SOPOrderReturn.CustomerDocumentNo 
          END, 
          Floyd.dbo.SOPInvoiceCredit.InvoicedNetValue, 
          Floyd.dbo.SOPInvoiceCredit.InvoicedTaxValue, 
          Floyd.dbo.SOPInvoiceCredit.InvoicedGrossValue, 
          Floyd.dbo.SOPInvCredDelAddress.PostalName, 
          Floyd.dbo.SOPInvCredDelAddress.AddressLine1, 
          Floyd.dbo.SOPInvCredDelAddress.PostCode 

Open in new window

0
 

Author Closing Comment

by:TeDeSm
ID: 39674788
Good comments but found using Common Table Expressions (cte) solution easier to follow giving me the correct results.
0

Featured Post

Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
SQL Query 2 63
execute a MS SQL script as a schedule SQL job 72 137
Two tables - Sum of values - What is the difference 31 54
Parse this column 6 23
INTRODUCTION: While tying your database objects into builds and your enterprise source control system takes a third-party product (like Visual Studio Database Edition or Red-Gate's SQL Source Control), you can achieve some protection using a sing…
In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

792 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question