Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 122
  • Last Modified:

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

0
pzozulka
Asked:
pzozulka
  • 2
  • 2
  • 2
  • +1
1 Solution
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
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
 
pzozulkaAuthor Commented:
Thanks, but same error message.
0
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
pzozulkaAuthor Commented:
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
 
PortletPaulCommented:
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
 
HuaMinChenBusiness AnalystCommented:
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
 
PortletPaulCommented:
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 SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

  • 2
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now