Solved

SQL error on Order By

Posted on 2014-11-07
7
108 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 46

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 46

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

 
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

Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

Question has a verified solution.

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

For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

910 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

21 Experts available now in Live!

Get 1:1 Help Now