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
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.
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.
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.
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.
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With