I have created a SQL query that works perfect for fetching the data needed. However I can not get it to Order by a column that is not present in the SELECT section. I found a similar question that was answered, but could not understand exactly what it was doing.
I'm trying to get the whole output to be sorted by 'CustomerLastName' but not have the that column show in the output file.
I have:
SELECT SUBSTRING(CustomerNumber, PATINDEX('%[^0]%', CustomerNumber+'.'), LEN(CustomerNumber)),'D','CAFET','', sum(Total) as totalsales
FROM ViewDetailedSalesReport
WHERE DateSold BETWEEN ('20200101') AND DateADD(day,1,'20200131')
GROUP BY CustomerNumber
ORDER BY CustomerLastName ASC
I know from reading other articles that I can not Order by something that is not in the SELECT portion, but can't quite understand how to use a 'non-declared' column to order by.
SELECT, but in this caseCustomerLastNameisn't in yourGROUP BYso it can't be. You just need to addCustomerLastNameto theGROUP BYclause. as I assumeCustomerNumberis unique to a customer.CustomerNumberis unique, however theCustomerLastNameis not, I was under the impression that the GROUP BY would be how the data is totaled together, thus I wouldn't want a non-uniqe field in that section? So if I understand you correctly I should be able to useGROUP BY CustomerNumber, CustomerLastNameORDER BY CustomerLastName ASCIs that how it would look?CustomerLastNameis going to be a consistent value for a givenCustomerNumber, so won't change the end results.