Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL sorting by a calculated column

Tags:

sql

tsql

I have a table with these columns: ID, Price, IsMonthlyPrice

How can I select all and sort by weekly price, taking into account that:

if (IsMonthlyPrice = false) then Price is weekly

EDIT:

I need to sort by weekly price

weekly price of a monthly price would be: Price*12/52

like image 528
user441365 Avatar asked Dec 21 '11 14:12

user441365


People also ask

Can you index a computed column?

Create indexes on persisted computed columnsYou can do this when the column is marked PERSISTED in the CREATE TABLE or ALTER TABLE statement. This means that the Database Engine stores the computed values in the table, and updates them when any other columns on which the computed column depends are updated.

How do I sort a column by value in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.

Can you ORDER BY a SELECT statement?

SQL queries initiated by using a SELECT statement support the ORDER BY clause. The result of the SELECT statement is sorted in an ascending or descending order.

How do you use ORDER BY clause with SQL statement?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.


3 Answers

You don't need to include the calculation twice. You can order on the column number

SELECT 
    ID, 
    Price, 
    IsMonthlyPrice, 
    CASE IsMonthlyPrice
    WHEN 1 THEN Price * 12 / 52
    ELSE price
    END
FROM [TABLE]
    order by 
        4
like image 192
Po-ta-toe Avatar answered Nov 15 '22 12:11

Po-ta-toe


Not sure if this is what you look for but maybe try:

select 
    id,
    case isMonthlyPrice when 'false' then (price*52/12) else price end normalizedPrice
from
    yourTable
order by
    normalizedPrice
like image 35
jjmontes Avatar answered Nov 15 '22 11:11

jjmontes


You can sort calculated columns using two approaches. The more verbal approach (untested pseudocode) is:

select ID, CASE WHEN IsMonthlyPrice = 0 THEN Price * 52 / 12 ELSE Price END AS Price
ORDER BY CASE WHEN IsMonthlyPrice = 0 THEN Price * 52 / 12 ELSE Price END

The more concise approach is:

select * from
(
select ID, CASE WHEN IsMonthlyPrice = 0 THEN Price * 52 / 12 ELSE Price END AS Price
) as derived
ORDER BY derived.Price 
like image 20
Shan Plourde Avatar answered Nov 15 '22 12:11

Shan Plourde