我的选择查询中有2个案例陈述: -
case
when substr(tariff_name,1,1) = 'S' then
case
when t.utility = 'Water' then '107.96'
when t.utility = 'Foam' then '104.96'
end
when substr(tariff_name,1,1) = 'J' then
case
when t.utility = 'Water' then '90.88'
when t.utility = 'Foam' then '70.07'
end
end AS Annual_SC_Cost,
case
when substr(tariff_name,1,1) = 'S' then
case
when t.utility = 'Water' then eac * 0.11821
when t.utility = 'Foam' then eac * 0.02707
end
when substr(tariff_name,1,1) = 'J' then
case
when t.utility = 'Water' then eac * 0.1338
when t.utility = 'Foam' then eac * 0.03055
end
end AS Annual_Cons_Cost
我想做的是另一个基本上是这样的选择:
case
when t.tlength = 12 then (Annual_SC_Cost * Annual_Cons_Cost) * 1
when t.tlength = 24 then (Annual_SC_Cost * Annual_Cons_Cost) * 2
end
这是否可行,如果没有,是否有另一种方法可以将计算保存到单个SQL查询中?
答案 0 :(得分:1)
对于您展示的非常具体的计算,假设您只需要最终计算的结果(并且您不需要在第一个代码片段中创建的中间结果),您可以重新排列代码,以便每个计算都是做了一次。您甚至不需要别名来获得中间结果。像这样:
product
其他说明:var termsArray = [];
var channelsArray = [];
for (var i = 0; i < productData.length; i++) {
for(var j = 0; j < productData[i].termsArr.length; j++){
termsArray.push(productData[i].termsArr[j])
}
for(var k = 0; k < productData[i].channelsArr.length; k++){
channelsArray.push(productData[i].channelsArr[k])
}
}
相当于...
,
case <calculation that produces annual_sc_cost> end
*
case <calculation that produces annual_cons_cost> end
*
case t.length when 12 then 1 when 24 then 2 end
,通常效率更高。此外,正如我在上面tariff_name like 'S%'
演示的那样,您可以更简洁地编写substr(tariff_name, 1, 1,) = 'S'
表达式,将某些内容与固定值进行比较。 (阅读“简单”与“搜索”案例表达式 - 谷歌搜索这些短语;这个概念非常基本,不易理解和使用)。
答案 1 :(得分:0)
也许是这样的:
case
when substr(tariff_name,1,1) = 'S' then
case
when t.utility = 'Water' then '107.96'
when t.utility = 'Foam' then '104.96'
end
when substr(tariff_name,1,1) = 'J' then
case
when t.utility = 'Water' then '90.88'
when t.utility = 'Foam' then '70.07'
end
end AS Annual_SC_Cost,
case
when substr(tariff_name,1,1) = 'S' then
case
when t.utility = 'Water' then eac * 0.11821
when t.utility = 'Foam' then eac * 0.02707
end
when substr(tariff_name,1,1) = 'J' then
case
when t.utility = 'Water' then eac * 0.1338
when t.utility = 'Foam' then eac * 0.03055
end
end AS Annual_Cons_Cost
将第一个查询用作子字符串并再次加入表格。
答案 2 :(得分:0)
您可以将查询用作内联视图,并对相应的别名字段执行操作,如下所示 -
SELECT CASE
WHEN t.tlength = 12 THEN (Annual_SC_Cost * Annual_Cons_Cost) * 1
WHEN t.tlength = 24 THEN (Annual_SC_Cost * Annual_Cons_Cost) * 2
END final_output
FROM (SELECT CASE
WHEN SUBSTR (tariff_name, 1, 1) = 'S'
THEN
CASE
WHEN t.utility = 'Water' THEN '107.96'
WHEN t.utility = 'Foam' THEN '104.96'
END
WHEN SUBSTR (tariff_name, 1, 1) = 'J'
THEN
CASE
WHEN t.utility = 'Water' THEN '90.88'
WHEN t.utility = 'Foam' THEN '70.07'
END
END
AS Annual_SC_Cost,
CASE
WHEN SUBSTR (tariff_name, 1, 1) = 'S'
THEN
CASE
WHEN t.utility = 'Water' THEN eac * 0.11821
WHEN t.utility = 'Foam' THEN eac * 0.02707
END
WHEN SUBSTR (tariff_name, 1, 1) = 'J'
THEN
CASE
WHEN t.utility = 'Water' THEN eac * 0.1338
WHEN t.utility = 'Foam' THEN eac * 0.03055
END
END
AS Annual_Cons_Cost
FROM t)