Solved

How To - SubQuery to replace MAX DISTINCT

Posted on 2013-11-18
6
395 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 38

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
Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

 

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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

I am showing a way to read/import the excel data in table using SQL server 2005... Suppose there is an Excel file "Book1" at location "C:\temp" with column "First Name" and "Last Name". Now to import this Excel data into the table, we will use…
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

760 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now