2

I'm simply trying to use min() and max() functions in an expression like so:

SELECT WSN, MIN(TOP) - MAX(BASE) FROM PERFS GROUP BY WSN 

But this doesn't appear to be valid SQL. I keep getting told I can't use aggregate functions in an expression. Could I get some help?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
John
  • 485
  • 3
  • 5
  • 16

5 Answers5

5

Without the database platform we can't tell that much, but try this:

select wsn, top - base
from
( SELECT WSN
  ,      MIN(TOP) top
  ,      MAX(BASE) base
  FROM   PERFS
  GROUP
  BY     WSN
)

I think the actual answer can be found in the documentation where you can find that TOP is a keyword indeed and tables are escaped with ".

Try this:

SELECT WSN
,      MIN("TOP") - MAX(BASE)
FROM   PERFS
GROUP
BY     WSN
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
2

I threw the question onto the DBISAM forum at Elevate (not sure why I didn't do that to begin with), and this is what they came up with:

Use two passes and create a memory table.

SELECT WSN, MAX(BASE) as MaxBase, MIN(TOP) as MinTop INTO memory FirstPass FROM PERFS GROUP BY WSN
;
SELECT (MaxBase - MinTop) as Calc FROM memory FirstPass

Thanks for all of the help guys.

John
  • 485
  • 3
  • 5
  • 16
1

The best answer might depend on what type of SQL you're using, as a common table expression would come in really handy for this. I assume TOP and BASE are fields in the PERFS table?

Here's my best guess:

SELECT WSN, (select MIN(TOP) FROM PERFS GROUP BY WSN) - (select MAX(BASE) FROM PERFS GROUP BY WSN) FROM PERFS GROUP BY WSN

Edit: Patrick's answer would probably be better.

Adam Miller
  • 767
  • 1
  • 9
  • 22
0

This works for me using Oracle. What DBMS are you using?

The statement below creates a sample inline table that you can query against. I provided example code here that can be run as-is (self contained). You have to adapt it to match your own database schema:

WITH TEST_DATA AS (
  SELECT 'ted' AS name, 1 as val FROM DUAL UNION ALL 
  SELECT 'ted' AS name, 2 as val FROM DUAL UNION ALL 
  SELECT 'ted' AS name, 3 as val FROM DUAL UNION ALL 
  SELECT 'sam' AS name, 5 as val FROM DUAL UNION ALL 
  SELECT 'sam' AS name, 10 as val FROM DUAL
)SELECT name, MIN(val) - MAX(val) as minmax
 FROM TEST_DATA
GROUP BY name
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Michael Ford
  • 851
  • 6
  • 9
0
select MAX(population) - MIN(population) as value from city;

where the query is to find the max - min from population in the city table

value- is the variable name where it can be changed to any

Neo_17
  • 1