Solved

How To - SubQuery to replace MAX DISTINCT

Posted on 2013-11-18
6
406 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Introduction: When running hybrid database environments, you often need to query some data from a remote db of any type, while being connected to your MS SQL Server database. Problems start when you try to combine that with some "user input" pass…
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

749 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