Solved

SQL error on Order By

Posted on 2014-11-07
7
105 Views
Last Modified: 2014-11-21
I am getting the error message below, and not sure why. The ORDER BY items are for sure in the SELECT list.

ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

SELECT DISTINCT
	RT.PartyId as 'PartyId', RT.Code as 'SubmittedByCode', RT.EntityName as 'SubmittedByName', RT.EntryDate as 'CreateDate',
	bc.Name as 'GroupCategory', bc.[Description] as 'TerritoryDescription', bc.BusinessGroupId as 'TerritoryID',
	sp.Code as 'SalesCode', sp.Name1 as 'SalespersonName',
	ISNULL(ACtotal.Accounts,0) as 'Accounts', ISNULL(ACtotal.AmountFinanced,0) as 'AmountFinanced'
FROM 
	#tmpRef RT
	left join (               
	   SELECT ebcm.EntityId  ,    
	   bc.BusinessCategoryId,    
	   bc.[Description],    
	   bc.Name,    
	   bc.BusinessGroupId,    
	   ROW_NUMBER() OVER(PArtition by ebcm.EntityId    ORDER BY bc.name) AS seq    
	    
	   FROM EntityBusinessCategoryMap ebcm    
	   LEFT JOIN  BusinessCategory bc ON  bc.BusinessCategoryId = ebcm.BusinessCategoryId    
	   left join BusinessGroup bg on bg.BusinessGroupId = bc.BusinessGroupId      
	   WHERE bg.Name = 'Territory'  AND     
		  (@specificTerritory is null OR bc.BusinessCategoryId IN (select * from @TerritoryList))                 
		)  bc on bc.EntityId = RT.PartyId   AND  bc.seq = 1      
	----  
	left join Entity sp on sp.PartyId = RT.SalespersonId 
	left join -- # of Accounts Total, AmountFinanced Total
	 (
		SELECT
			CuAc.SubmittedById,
			Count(1) as 'Accounts',
			SUM(PFL.AmountFinanced) as 'AmountFinanced'
		FROM
			CustomerAccount CuAc
			LEFT JOIN PremiumFinanceLoan PFL ON PFL.CustomerAccountId = CuAc.PartyId AND PFL.IsOriginal = 1
						
		WHERE
			(@specificSubmittedBy is null OR CuAc.SubmittedById IN (select * from @SubmittedByList)) 
			AND CuAc.AccountCreateDate between @startDate and @endDate
		GROUP BY
			CuAc.SubmittedById
	 ) as ACtotal on ACtotal.SubmittedById = RT.PartyId

ORDER BY CASE @sortBy WHEN 'Submitted By Code' THEN RT.Code ELSE NULL END,
		 CASE @sortBy WHEN 'Submitted By Name' THEN RT.EntityName ELSE NULL END

Open in new window

0
Comment
Question by:pzozulka
  • 2
  • 2
  • 2
  • +1
7 Comments
 
LVL 45

Expert Comment

by:Vitor Montalvão
ID: 40428776
No need for ELSE:
SELECT DISTINCT
	RT.PartyId as 'PartyId', RT.Code as 'SubmittedByCode', RT.EntityName as 'SubmittedByName', RT.EntryDate as 'CreateDate',
	bc.Name as 'GroupCategory', bc.[Description] as 'TerritoryDescription', bc.BusinessGroupId as 'TerritoryID',
	sp.Code as 'SalesCode', sp.Name1 as 'SalespersonName',
	ISNULL(ACtotal.Accounts,0) as 'Accounts', ISNULL(ACtotal.AmountFinanced,0) as 'AmountFinanced'
FROM 
	#tmpRef RT
	left join (               
	   SELECT ebcm.EntityId  ,    
	   bc.BusinessCategoryId,    
	   bc.[Description],    
	   bc.Name,    
	   bc.BusinessGroupId,    
	   ROW_NUMBER() OVER(PArtition by ebcm.EntityId    ORDER BY bc.name) AS seq    
	    
	   FROM EntityBusinessCategoryMap ebcm    
	   LEFT JOIN  BusinessCategory bc ON  bc.BusinessCategoryId = ebcm.BusinessCategoryId    
	   left join BusinessGroup bg on bg.BusinessGroupId = bc.BusinessGroupId      
	   WHERE bg.Name = 'Territory'  AND     
		  (@specificTerritory is null OR bc.BusinessCategoryId IN (select * from @TerritoryList))                 
		)  bc on bc.EntityId = RT.PartyId   AND  bc.seq = 1      
	----  
	left join Entity sp on sp.PartyId = RT.SalespersonId 
	left join -- # of Accounts Total, AmountFinanced Total
	 (
		SELECT
			CuAc.SubmittedById,
			Count(1) as 'Accounts',
			SUM(PFL.AmountFinanced) as 'AmountFinanced'
		FROM
			CustomerAccount CuAc
			LEFT JOIN PremiumFinanceLoan PFL ON PFL.CustomerAccountId = CuAc.PartyId AND PFL.IsOriginal = 1
						
		WHERE
			(@specificSubmittedBy is null OR CuAc.SubmittedById IN (select * from @SubmittedByList)) 
			AND CuAc.AccountCreateDate between @startDate and @endDate
		GROUP BY
			CuAc.SubmittedById
	 ) as ACtotal on ACtotal.SubmittedById = RT.PartyId

ORDER BY CASE @sortBy WHEN 'Submitted By Code' THEN RT.Code END,
		 CASE @sortBy WHEN 'Submitted By Name' THEN RT.EntityName END

Open in new window

0
 
LVL 8

Author Comment

by:pzozulka
ID: 40428786
Thanks, but same error message.
0
 
LVL 45

Expert Comment

by:Vitor Montalvão
ID: 40428817
Seems like you need to pass the CASE to the SELECT list:
SELECT DISTINCT
	RT.PartyId as 'PartyId', CASE @sortBy WHEN 'Submitted By Code' THEN RT.Code END, CASE @sortBy WHEN 'Submitted By Name' THEN RT.EntityName END, RT.EntryDate as 'CreateDate',
	bc.Name as 'GroupCategory', bc.[Description] as 'TerritoryDescription', bc.BusinessGroupId as 'TerritoryID',
	sp.Code as 'SalesCode', sp.Name1 as 'SalespersonName',
	ISNULL(ACtotal.Accounts,0) as 'Accounts', ISNULL(ACtotal.AmountFinanced,0) as 'AmountFinanced'
FROM 
	#tmpRef RT
	left join (               
	   SELECT ebcm.EntityId  ,    
	   bc.BusinessCategoryId,    
	   bc.[Description],    
	   bc.Name,    
	   bc.BusinessGroupId,    
	   ROW_NUMBER() OVER(PArtition by ebcm.EntityId    ORDER BY bc.name) AS seq    
	    
	   FROM EntityBusinessCategoryMap ebcm    
	   LEFT JOIN  BusinessCategory bc ON  bc.BusinessCategoryId = ebcm.BusinessCategoryId    
	   left join BusinessGroup bg on bg.BusinessGroupId = bc.BusinessGroupId      
	   WHERE bg.Name = 'Territory'  AND     
		  (@specificTerritory is null OR bc.BusinessCategoryId IN (select * from @TerritoryList))                 
		)  bc on bc.EntityId = RT.PartyId   AND  bc.seq = 1      
	----  
	left join Entity sp on sp.PartyId = RT.SalespersonId 
	left join -- # of Accounts Total, AmountFinanced Total
	 (
		SELECT
			CuAc.SubmittedById,
			Count(1) as 'Accounts',
			SUM(PFL.AmountFinanced) as 'AmountFinanced'
		FROM
			CustomerAccount CuAc
			LEFT JOIN PremiumFinanceLoan PFL ON PFL.CustomerAccountId = CuAc.PartyId AND PFL.IsOriginal = 1
						
		WHERE
			(@specificSubmittedBy is null OR CuAc.SubmittedById IN (select * from @SubmittedByList)) 
			AND CuAc.AccountCreateDate between @startDate and @endDate
		GROUP BY
			CuAc.SubmittedById
	 ) as ACtotal on ACtotal.SubmittedById = RT.PartyId

ORDER BY CASE @sortBy WHEN 'Submitted By Code' THEN RT.Code END,
		 CASE @sortBy WHEN 'Submitted By Name' THEN RT.EntityName END

Open in new window

0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 8

Author Comment

by:pzozulka
ID: 40428925
This breaks my SELECT statement because when they choose to order by 'Submitted by Code' the query does not display the 'Submitted By Name' and vice versa.
0
 
LVL 48

Expert Comment

by:PortletPaul
ID: 40429682
Have you tried this query without "select distinct'?

Ideally 'distinct' should not be needed. You are using a temp table so you most probably have full control on what goes in it, so these should not need distinct:

    RT.PartyId AS 'PartyId'
  , RT.Code AS 'SubmittedByCode'
  , RT.EntityName AS 'SubmittedByName'
  , RT.EntryDate AS 'CreateDate'

You are using row_number() in the subquery aliased as BC so "AND BC.seq = 1" means these will not multiply the number of rows:

, BC.Name AS 'GroupCategory'
, BC.[Description] AS 'TerritoryDescription'
, BC.BusinessGroupId AS 'TerritoryID'

Which leaves just aliases SP and ACTOTAL, and ACTOTAL is already being grouped.

So why is "distinct" needed? What columns produce unwanted repetition? Solve that.
0
 
LVL 10

Expert Comment

by:HuaMinChen
ID: 40429940
Hi,
You cannot put relevant columns to case clause above, unless you use Dynamic Sql (sp_executesql), to do the same. Read
http://msdn.microsoft.com/en-us/library/ms188001.aspx
0
 
LVL 48

Accepted Solution

by:
PortletPaul earned 500 total points
ID: 40429948
It is possible to evaluate @parameter values in the ORDER BY clause as this example demonstrates:
|    TYPE |             DETAILS | COLUMN_2 |
|---------|---------------------|----------|
|   Email | admin@sqlfiddle.com |      abc |
| Twitter |          @sqlfiddle |      abc |
		
|    TYPE |             DETAILS | COLUMN_2 |
|---------|---------------------|----------|
| Twitter |          @sqlfiddle |  NOT abc |
|   Email | admin@sqlfiddle.com |  NOT abc |
		

Open in new window


declare @SortBy as varchar(200)

set @SortBy = 'abc'

select
       type, details, @SortBy
from supportContacts
order by
        case when @sortBy =  'abc' then type    else null end ASC
      , case when @sortBy <> 'abc' then details else null end ASC
;

Open in new window


declare @SortBy as varchar(200)

set @SortBy = 'NOT abc'

select
       type, details, @SortBy
from supportContacts
order by
        case when @sortBy =  'abc' then type    else null end ASC
      , case when @sortBy <> 'abc' then details else null end ASC
;

Open in new window

-- Now you can see how it works in 2012!
CREATE TABLE supportContacts 
	(
     id int identity primary key, 
     type varchar(20), 
     details varchar(30)
    );
 
INSERT INTO supportContacts
(type, details)
VALUES
('Email', 'admin@sqlfiddle.com'),
('Twitter', '@sqlfiddle');

Open in new window

also see: http://sqlfiddle.com/#!6/f5b23/9

But the matter of DISTINCT needs solution first
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

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.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

708 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

12 Experts available now in Live!

Get 1:1 Help Now