Solved

SQL error on Order By

Posted on 2014-11-07
7
109 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 47

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 47

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
Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

 
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

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
2016 SQL Licensing 7 40
SQL Server 2012 - Merge Replication Issue 1 19
Increment column based of a FK 8 20
Help in Bulk Insert 9 30
In this article I will describe the Detach & Attach method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Via a live example, show how to shrink a transaction log file down to a reasonable size.

776 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