Isaac,
Your algorithm requires between 3 and 6 comparisons for each set of
dates, and I believe it requires an average of 2+2ln2, or about 3.386,
comparisons for random (date1, date2, date3, date4) values chosen from
the same large range of dates (in the limit as the date range grows
large). You can get by with exactly 3 comparisons regardless of values
this way (if we have storage available for two intermediate results):
select
foo_id,
case when date12 >= date34 then date12 else date34 end as MaxDate
from (
select date1, date2, date3, date4,
case when date1 >= date2 then date1 else date2 end as date12,
case when date3 >= date4 then date3 else date4 end as date34
from Foobar
) as Foobar
Of course there's no guarantee that the optimizer will preserve this
efficiency.
SK
[quoted text, click to view] Isaac Blank wrote:
>I have always thought order of evaluation in CASE expressions is always top
>to bottom. If that's true, then one can save a few CPU cycles:
>
>CREATE VIEW BigFoo (foo_id, latest_date)
>AS
>SELECT foo_id,
> CASE WHEN date1 >= date2
> AND date1 >= date3
> AND date1 >= date4
> THEN date1
> WHEN date2 >= date3
> AND date2 >= date4
> THEN date2
> WHEN date3 >= date4
> THEN date3
> ELSE date4 END
> FROM Foobar;
>
>"Joe Celko" <joe.celko@northface.edu> wrote in message
>news:eg5BzLXAEHA.3712@tk2msftngp13.phx.gbl...
>
>
>>Please post DDL, so that people do not have to guess what the keys,
>>constraints, Declarative Referential Integrity, datatypes, etc. in your
>>schema are. Here is an unsupported guess at what you might have meant
>>to say:
>>
>>CREATE TABLE Foobar
>>(foo_id INTEGER NOT NULL PRIMARY KEY,
>> date1 DATETIME NOT NULL,
>> date2 DATETIME NOT NULL,
>> date3 DATETIME NOT NULL,
>> date4 DATETIME NOT NULL);
>>
>>
>>
>>>> need a SQL statement that will let me find out the
>>>>
>>>>
>>largest date in Date1 to Date4 for each row <<
>>
>>If you put it into a VIEW, it will update itself.
>>
>>CREATE VIEW BigFoo (foo_id, latest_date)
>>AS
>>SELECT foo_id,
>> CASE WHEN date1 >= date2
>> AND date1 >= date3
>> AND date1 >= date4
>> THEN date1
>> WHEN date2 >= date1
>> AND date2 >= date3
>> AND date2 >= date4
>> THEN date2
>> WHEN date3 >= date1
>> AND date3 >= date2
>> AND date3 >= date4
>> THEN date3
>> ELSE date4 END
>> FROM Foobar;
>>
>>
>>
>>--CELKO--
>>
>>
>>*** Sent via Developersdex
http://www.developersdex.com ***
>>Don't just participate in USENET...get rewarded for it!
>>
>>
>
>
>