我有一个包含这些列的表:ID, Price, IsMonthlyPrice
我如何选择所有并按周价格排序,并考虑到:
if (IsMonthlyPrice = false) then Price is weekly
编辑:
我需要按每周价格排序
每月价格的每周价格为:价格* 12/52
答案 0 :(得分:17)
您不需要包含两次计算。您可以订购列号
SELECT
ID,
Price,
IsMonthlyPrice,
CASE IsMonthlyPrice
WHEN 1 THEN Price * 12 / 52
ELSE price
END
FROM [TABLE]
order by
4
答案 1 :(得分:4)
不确定这是否是您所寻求的,但也许可以尝试:
select
id,
case isMonthlyPrice when 'false' then (price*52/12) else price end normalizedPrice
from
yourTable
order by
normalizedPrice
答案 2 :(得分:3)
您可以使用两种方法对计算列进行排序。更加口头的方法(未经测试的伪代码)是:
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
更简洁的方法是:
select * from
(
select ID, CASE WHEN IsMonthlyPrice = 0 THEN Price * 52 / 12 ELSE Price END AS Price
) as derived
ORDER BY derived.Price
答案 3 :(得分:0)
我通常将选择包装在另一个中。然后该列不再“计算”
select Price, ID from (select ID, Price, [calculate the IsMonthly Price] as 'IsMonthlyPrice' from table) order by IsMonthlyPrice
答案 4 :(得分:0)
您可以使用case
计算不同的值,具体取决于价格是每周还是每月。
这将计算每天的近似值(假设每月31天)以进行排序:
select ID, Price, IsMonthlyPrice
from TheTable
order by Price / case IsMonthlyPrice when 1 then 31.0 else 7.0 end