0

I am struggling to simplify / alias the following SQL query. I am fairly new to SQL, hopefully someone can point me to the right direction.

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".

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

3 Answers 3

0

Try using conditional aggregation:

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

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
1
  • Thanks Matt, it might be my SQLite, it's not letting me use IF function. But yes, that's definitely a more elegant way of doing it. I'll just have to take the difference in value of the 2 rows I assume.
    – DanC
    Oct 17, 2017 at 18:26
0

Mysql Developers Team announced that version 8.0 will have Common Table Expressions in MySQL (CTEs). 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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.