2

In this SQL query:

select
name,
age,
(select sum(something) from sometable where sometable.code = people.code)
from people
where THIRD_COLUMN > 0

How to reference the result of the third column without having to repeat the SQL?

Mateus Viccari
  • 7,389
  • 14
  • 65
  • 101

2 Answers2

3

You can't. You can use a subquery and give the column a name, though:

select p.name, p.age, p.THIRD_COLUMN
from (select name, age,
             (select sum(something) from sometable where sometable.code = people.code
             ) as THIRD_COLUMN
      from people
     ) p
where THIRD_COLUMN > 0;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
-1

I dont know which dms you use but in mysql you can use:

select
name,
age,
(select sum(something) from sometable where sometable.code = people.code) sum_people
from people
having sum_people > 0
srit83
  • 32
  • 2
  • Having without group? – Giorgi Nakeuri Apr 16 '15 at 14:58
  • You're right! ;-) The correct statement can build like this: select id, name, age, (select sum(something) from sometable where sometable.code = people.code) sum_people from people group by id having sum_people > 0 Thx for your hint. ;-) – srit83 Apr 17 '15 at 07:48