Re: retrieving top 1 of ordered union
From: Joe Celko (jcelko212_at_earthlink.net)
Date: 08/11/04
- Next message: Adam Machanic: "Re: Output parameter with SP"
- Previous message: Aaron [SQL Server MVP]: "Re: Output parameter with SP"
- In reply to: Bob Clegg: "retrieving top 1 of ordered union"
- Messages sorted by: [ date ] [ thread ]
Date: Wed, 11 Aug 2004 07:32:35 -0700
>> Can any one tell me the syntax for this? As soon as the union
statement becomes a subquery it gets bitter and
twisted about the order by clause. <<
Syntax is not your problem. You think that SQL's UNION is the same
thing as a tape file merge. The **most basic** idea of an RDBMS is that
tables have no ordering -- they are sets.
Furthermore, the result of a UNION has no column names, so your AS
clauses were useless. The standard syntax is CURRENT_TIMESTAMP, not the
proprietary getdate().
Since you type your parts of the code in only one case and use minimal
spacing, I would guess you began programming in the punch card days and
are trying to un-learn the old stuff.
Here is a kludge that involves making the UNION into a derived table:
SELECT X.read_date
FROM (SELECT scheduled_read_date
FROM AMRChannel
WHERE amr_id = @amr_id
AND DATEDFF(d, CURRENT_TIMESTAMP, scheduled_read_date) >= 1
UNION
SELECT scheduled1_read_date
FROM AMRChannel
WHERE amr_id = @amr_id
AND DATEDFF(d, CURRENT_TIMESTAMP, scheduled1_read_date) >= 1)
AS X(read_date);
Two red flags went up in this code.
1) A UNION with the same table in the SELECTs can be almost always be
rewritten with an OR and run in half the time.
2) When I see two columns with identical names and a number, I get very
afraid that we have an attempt to model an array in SQL to get around
1NF and make it look like a tape file.
They are totally, logically different, aren't they? But then putting
them into one column would be weird, like a column of apples and
bagpipes.
So why not write this?
SELECT scheduled_read_date, scheduled1_read_date
FROM AMRChannel
WHERE amr_id = @amr_id
AND DATEDFF(d, CURRENT_TIMESTAMP, scheduled_read_date) >= 1
AND DATEDFF(d, CURRENT_TIMESTAMP, scheduled1_read_date) >= 1);
This might not work thanks to NULLs, but since you did not bother to
post DDL, we can only guess.
--CELKO--
===========================
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are.
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
- Next message: Adam Machanic: "Re: Output parameter with SP"
- Previous message: Aaron [SQL Server MVP]: "Re: Output parameter with SP"
- In reply to: Bob Clegg: "retrieving top 1 of ordered union"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|
|