Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

Order By with a Case on an aliased aggregate column in SQL Server not working

Objectives

I would like to pass TopOrWorst and date ranges as parameters into a stored procedure. It should return Top Or Worst 10 products based on the sum of sales values between the dates range provided.

I have hardcoded the date ranges in the query and create a variable @TopOrWorst for simplicity.

Below are 3 different queries, out of which latter 2 works, but I wanted the 1st one to work for me.

DECLARE @TopOrWorst INT = 1; -- 1 = Top, 2= Worst

-- Query #1: sorting DOES NOT work when the column alias 
-- is used inside the case statement.
SELECT TOP 10 
    sh.Stockcode,
    SUM(sh.SalesValue) AS TotalSales 
FROM 
    SalesHistory sh 
WHERE 
    DateSold BETWEEN '2017-05-05' AND '2017-05-10'
GROUP BY 
    sh.Stockcode
ORDER BY 
    CASE WHEN @TopOrWorst = 1 THEN TotalSales END DESC,
    CASE WHEN @TopOrWorst = 2 THEN TotalSales END  

-- Query #2: sorting works when then column is SUMed inside the case statement.

SELECT TOP 10 
    sh.Stockcode,
    SUM(sh.SalesValue) AS TotalSales 
FROM 
    SalesHistory sh 
WHERE 
    DateSold BETWEEN '2017-05-05' AND '2017-05-10'
GROUP BY 
    sh.Stockcode
ORDER BY 
    CASE WHEN @TopOrWorst = 1 THEN SUM(sh.salesvalue) END DESC,
    CASE WHEN @TopOrWorst = 2 THEN SUM(sh.salesvalue) END  

-- Query #3: sorting works with the Alias field without the case statement.
SELECT TOP 10 
    sh.Stockcode,
    SUM(sh.SalesValue) AS TotalSales 
FROM 
    SalesHistory sh 
WHERE 
    DateSold BETWEEN '2017-05-05' AND '2017-05-10'
GROUP BY 
    sh.Stockcode
ORDER BY 
    TotalSales DESC  

What is wrong with query #1 ? Appreciate all the help in advance.

Thanks

question from:https://stackoverflow.com/questions/65832687/order-by-with-a-case-on-an-aliased-aggregate-column-in-sql-server-not-working

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

SQL Server allows aliases to be used in ORDER BY -- all alone.

SQL Server does not allow aliases to be part of an expression. Something as simple as TotalSales + 1 won't work either.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...