Avatar of pzozulka
pzozulka
 asked on

SQL error on Order By

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

Microsoft SQL ServerMicrosoft SQL Server 2005Microsoft SQL Server 2008

Avatar of undefined
Last Comment
PortletPaul

8/22/2022 - Mon
Vitor Montalvão

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

pzozulka

ASKER
Thanks, but same error message.
Vitor Montalvão

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

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
pzozulka

ASKER
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.
PortletPaul

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.
Peter Chan

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
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
ASKER CERTIFIED SOLUTION
PortletPaul

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.