Difference between revisions of "Maximum"

From SQLZOO
Jump to: navigation, search
(Created page with "Calculate the maximum or minimum of two fields <div class='ht'> <div class=params>schema:scott</div> <source lang=sql class='tidy'>DROP TABLE t</source> <source lang=sql class...")
 
 
(4 intermediate revisions by one user not shown)
Line 1: Line 1:
Calculate the maximum or minimum of two fields
+
In this example you are shows how to use the MAX or MIN functions to find the maximum or minimum over two fields instead of just one.
 
<div class='ht'>
 
<div class='ht'>
 
<div class=params>schema:scott</div>
 
<div class=params>schema:scott</div>
Line 12: Line 12:
 
</source>
 
</source>
 
<div>
 
<div>
<p>The function for using MAX over two fields is</p>
+
<p>The function for using <code>MAX</code> over two fields is</p>
 
  max(x,y) = (x + y + ABS(x-y))/2
 
  max(x,y) = (x + y + ABS(x-y))/2
<p>The function for using MIN over two fields is</p>
+
<p>The function for using <code>MIN</code> over two fields is</p>
 
  min(x,y) = (x + y - ABS(x-y))/2
 
  min(x,y) = (x + y - ABS(x-y))/2
 
</div>
 
</div>
<source lang='sql' class='def'>SELECT id, x, y, (x+y+ABS(x-y))/2  
+
<source lang='sql' class='def'>
FROM t</source>
+
SELECT id, x, y, (x+y+ABS(x-y))/2  
<div class="ecomm e-mysql" style="display: none"></div>
+
  FROM t</source>
<div class="ecomm e-oracle" style="display: none"></div>
+
<div class="ecomm e-mysql" style="display: none">In MySQL you can also use the <code>GREATEST</code> or <code>LEAST</code> functions to do this.</div>
 +
<div class="ecomm e-oracle" style="display: none">In Oracle you can also use the <code>GREATEST</code> or <code>LEAST</code> functions to do this.</div>
 +
</div>
  
 
{{Hacks Ref}}
 
{{Hacks Ref}}

Latest revision as of 16:04, 2 August 2012

In this example you are shows how to use the MAX or MIN functions to find the maximum or minimum over two fields instead of just one.

schema:scott
DROP TABLE t
 CREATE TABLE t(
  id VARCHAR(10),
  x INTEGER,
  y INTEGER );
INSERT INTO t VALUES ('A',1,2);
INSERT INTO t VALUES ('B',4,3);
INSERT INTO t VALUES ('C',5,5);

The function for using MAX over two fields is

max(x,y) = (x + y + ABS(x-y))/2

The function for using MIN over two fields is

min(x,y) = (x + y - ABS(x-y))/2
SELECT id, x, y, (x+y+ABS(x-y))/2 
  FROM t
Personal tools
Namespaces

Variants
Actions
Reference
Toolbox
Google AdSense