Solved

How To - SubQuery to replace MAX DISTINCT

Posted on 2013-11-18
6
412 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Edgartown IT Case Study

Learn about Edgartown's quest to ensure the safety and security of the entire town's employee and citizen data. Read the case study!

 

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 41

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

Transaction Monitoring Vs. Real User Monitoring

Synthetic Transaction Monitoring Vs. Real User Monitoring: When To Use Each Approach? In this article, we will discuss two major monitoring approaches: Synthetic Transaction and Real User Monitoring.

Question has a verified solution.

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

There are some very powerful Data Management Views (DMV's) introduced with SQL 2005. The two in particular that we are going to discuss are sys.dm_db_index_usage_stats and sys.dm_db_index_operational_stats.   Recently, I was involved in a discu…
In this article I will describe the Backup & Restore 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.
This video Micro Tutorial shows how to password-protect PDF files with free software. Many software products can do this, such as Adobe Acrobat (but not Adobe Reader), Nuance PaperPort, and Nuance Power PDF, but they are not free products. This vide…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

726 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