我想做类似的事情:
Select
(select sum(monkey_value) from mt where monkey_weight > 20) ,
(select sum(monkey_value) from mt where monkey_weight > 30)
from MonkeyTable mt where monkeySanityLevel > 10
但我不能在子选择中使用mt。我现在所做的就是我声明了一个表并将父值的结果传递给它,并且在我自己查询子列表之后。
有没有更聪明的方法,所以我可以避免在临时表中插入行?
答案 0 :(得分:2)
怎么样
Select
Sum(case when monkey_weight > 20 then monkey_value else 0 end) as WT20,
Sum(case when monkey_weight > 30 then monkey_value else 0 end) as WT30
from MonkeyTable mt where monkeySanityLevel > 10
答案 1 :(得分:1)
以下应该工作:
select sum(case when monkey_weight > 20 then monkey_value end) as monkey_weight_20,
sum(case when monkey_weight > 30 then monkey_value end) as monkey_weight_30
from MonkeyTable mt
where monkeySanityLevel > 10
答案 2 :(得分:0)
其他答案都很好,但是使用CTE还可以做到这一点:
0
或另一种选择,使用单个子查询而不是CTE:
with mt as
(
select *
from MonkeyTable
where monkeySanityLevel > 10
)
select
sum(select monkey_value from mt where monkey_weight > 20) as WT20,
sum(select monkey_value from mt where monkey_weight > 30) as WT30