简体   繁体   English

我如何简化/别名此SQL查询

[英]How can I simplify / alias this SQL query

I am struggling to simplify / alias the following SQL query. 我正在努力简化/别名以下SQL查询。 I am fairly new to SQL, hopefully someone can point me to the right direction. 我对SQL还是比较陌生,希望有人可以指出正确的方向。

As the 2nd part of the line is pretty much identical to the 1st part other than the Where condition, I am hoping to just call it a variable "X". 由于该行的第2部分与第1部分几乎相同,除了Where条件,我希望将其称为变量“ X”。

I tried experimenting with different parentheses and order but I kept getting syntax error. 我尝试使用不同的括号和顺序进行试验,但始终收到语法错误。 My code is as follows: 我的代码如下:

select
(select avg(stars) from LONG EXPRESSION where Condition < Y)
-
(select avg(stars) from LONG EXPRESSION where Condition > Y)

Ideally I would like to achieve something similar to 理想情况下,我想实现类似于

select
(select avg(stars) from (LONG EXPRESSION) X where Condition < Y)
-
(select avg(stars) from X where Condition > Y)

Thanks for your help. 谢谢你的帮助。

Dan

I don't know your use case, but how about combining them into one query: 我不知道您的用例,但如何将它们组合成一个查询:

SELECT IF(Condition < Y, 'Less Than Y', 'GTE Y'), AVG(stars)
FROM long expression
GROUP BY 1

Mysql Developers Team announced that version 8.0 will have Common Table Expressions in MySQL (CTEs) . Mysql开发人员小组宣布8.0版将在MySQL(CTE)中具有通用表表达式 So it probably will be possible to write queries like this: 因此,可能可以编写如下查询:

WITH my_cte AS
(
 (LONG EXPRESSION)
)
select (select avg(stars) from (LONG EXPRESSION) X where Condition < Y) - (select avg(stars) from X where Condition > Y);

Try using conditional aggregation: 尝试使用条件聚合:

select avg(case when Condition < Y then stars end) -
       avg(case when Condition > Y then stars end)
from LONG EXPRESSION

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM