Solved

SELECT DISTINCT w/Join, ORDER BY in CASE

Posted on 2010-09-15
7
705 Views
Last Modified: 2012-08-13
Hello Experts,

Using MS SQL Server 2005...

Hopefully this is easy to solve.  I have a stored procedure that I use as a datasource for a drop down list.  This drop down list could contain a couple hundred items, so I provide the user with the ability to filter and sort the drop down list to help them find what they want to select.  So I have one optional parameter that filters the list, and another that changes the sort order.  Problem is, this query uses a join (1 to many), and my list comes up with duplicates.  No problem, just apply the DISTINCT predicate.  As soon as I do that, SQL Server complains that "ORDER BY items must appear in the select list if SELECT DISTINCT is specified".  I don't know what I need to specify in the select list because I'm using a case statement to order dynamically based on an input parameter.

Here is my stored procedure.  Please advise!


ALTER PROCEDURE [dbo].[jwSiteMetaData]
	@SiteID as int = null,
	@SiteType as varchar(50) = null,
	@SortOrder as varchar(20) = 'SD.SiteID'
AS
BEGIN
	SET NOCOUNT ON;

	IF @SiteType = '' SET @SiteType = null
	IF @SortOrder = 'SiteID' SET @SortOrder = 'SD.SiteID'

	SELECT DISTINCT convert(varchar,SD.SiteID) + ' - ' + SiteName AS SiteIDSiteName, SD.SiteID, SiteName 
	FROM SiteDef AS SD LEFT JOIN SiteTypes AS ST ON SD.SiteID=ST.SiteID
	WHERE SD.SiteID = coalesce(@SiteID,SD.SiteID)
		AND ST.SiteType = coalesce(@SiteType, ST.SiteType)
	ORDER BY
		CASE
			WHEN @SortOrder = 'SiteName' THEN (RANK() OVER (ORDER BY SiteName))
			ELSE (RANK() OVER (ORDER BY SD.SiteID))
		END
END

Open in new window

0
Comment
Question by:Jahelka
7 Comments
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 33682770
you migth want to read this article:
http://www.experts-exchange.com/A_3203.html

1 possibility might be this:

ALTER PROCEDURE [dbo].[jwSiteMetaData]
        @SiteID as int = null,
        @SiteType as varchar(50) = null,
        @SortOrder as varchar(20) = 'SD.SiteID'
AS
BEGIN
        SET NOCOUNT ON;

        IF @SiteType = '' SET @SiteType = null
        IF @SortOrder = 'SiteID' SET @SortOrder = 'SD.SiteID'

        SELECT SiteIDSiteName, SiteID, SiteName
          FROM ( 
           SELECT convert(varchar,SD.SiteID) + ' - ' + SiteName AS SiteIDSiteName
            , SD.SiteID, SiteName 
            , CASE 
              WHEN @SortOrder = 'SiteName' THEN (RANK() OVER (ORDER BY SiteName))
              ELSE (RANK() OVER (ORDER BY SD.SiteID))
               END rn
            FROM SiteDef AS SD 
            LEFT JOIN SiteTypes AS ST 
              ON SD.SiteID=ST.SiteID
           WHERE SD.SiteID = coalesce(@SiteID,SD.SiteID)
             AND ST.SiteType = coalesce(@SiteType, ST.SiteType)
        ) sq
        GROUP BY SiteIDSiteName, SiteID, SiteName
        ORDER BY MAX(rn)
                
END

Open in new window

0
 
LVL 51

Expert Comment

by:HainKurt
ID: 33682778
do this

if @SortOrder="..."
begin
  select ...
end

if @SortOrder="..."
begin
  select ...
end

use different simple statements instead of trying to order by complicated statements...
0
 
LVL 23

Expert Comment

by:Racim BOUDJAKDJI
ID: 33682830
Do what HainKurt suggested.  Better both for readability and performance.  (pls no poinks)
0
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
LVL 9

Accepted Solution

by:
Valliappan AN earned 500 total points
ID: 33682853
Try removing the distinct and use GROUP BY as attached. Hope that helps
ALTER PROCEDURE [dbo].[jwSiteMetaData]
	@SiteID as int = null,
	@SiteType as varchar(50) = null,
	@SortOrder as varchar(20) = 'SD.SiteID'
AS
BEGIN
	SET NOCOUNT ON;

	IF @SiteType = '' SET @SiteType = null
	IF @SortOrder = 'SiteID' SET @SortOrder = 'SD.SiteID'

	SELECT convert(varchar,SD.SiteID) + ' - ' + SiteName AS SiteIDSiteName, SD.SiteID, SiteName 
	FROM SiteDef AS SD LEFT JOIN SiteTypes AS ST ON SD.SiteID=ST.SiteID
	WHERE SD.SiteID = coalesce(@SiteID,SD.SiteID)
		AND ST.SiteType = coalesce(@SiteType, ST.SiteType)
        GROUP BY convert(varchar,SD.ID) + ' - ' + sd.Name , SD.ID, sd.Name
	ORDER BY
		CASE
			WHEN @SortOrder = 'SiteName' THEN (RANK() OVER (ORDER BY SiteName))
			ELSE (RANK() OVER (ORDER BY SD.SiteID))
		END
END

Open in new window

0
 
LVL 1

Author Closing Comment

by:Jahelka
ID: 33683037
I hadn't thought to use a Group By as I usually only use those in conjunction with max() or min() or one of those guys.  Nice, elegant solution!

HainKurt, wouldn't your solution be considered "dynamic sql" and mean that a query plan would have to be rebuilt each time the stored proc was run?  I can understand that sometimes readability and maintanance considerations can outweigh the performance considerations, but don't you want to try to avoid dynamic sql if at all possible?

Thanks for your very prompt and helpful responses guys.
0
 
LVL 23

Expert Comment

by:Racim BOUDJAKDJI
ID: 33683259
What Hainkurt suggest is not dynamic SQL.  dynamic SQL works by variabilizing strings which is different, and f course should be avoided for security reasons...
0
 
LVL 1

Author Comment

by:Jahelka
ID: 33683464
Ahh, OK.  I see the difference now that I look closer.  Each SQL statement would be complete on its own, you are just changing which one you execute based on the input parameter.  Apologies for the ignorance.  Thanks for the help.
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

786 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