Let's say I have the following table:
CREATE TABLE numbers
(
key integer NOT NULL DEFAULT 0,
number1 integer NOT NULL DEFAULT 0,
number2 integer NOT NULL DEFAULT 0,
number3 integer NOT NULL DEFAULT 0,
number4 integer NOT NULL DEFAULT 0,
CONSTRAINT pk PRIMARY KEY (key),
CONSTRAINT nonzero CHECK (key <> 0)
)
What I want to retrieve is the minimum value from a given key of all 4 numbers, but ignoring those that are zero.
I started with something like this when I figured that I'll have problem with the zeros:
SELECT LEAST(number1, number2, number3, number4) FROM numbers WHERE key = 1
For instance, if I have the tuple (1, 5, 0, 3, 2)
I want to return 2
, or for (2, 3, 0, 0, 0)
I want to return 3
and so on.
Can this be done in a single query (or maybe nested), I don't really want to have to write a procedure to do this.