Hi there. I have this query working very nicely for me at the moment. I'll need to add more to it so I'm interested in keeping it readable for the next poor sod who has to work on it.My question: The subquery in the WHEN statement is repeated in the THEN statement. Is there a way to avoid the repetition? e.g., In a scripting language one would assign the query to a variable so that If (ThisValue - PreviousValue) >= 0 Then output = ThisValue - PreviousValue Else output = ThisValue End If
could be simplified to x = ThisValue - PreviousValue If x >= 0 Then output = x Else output = ThisValue
which is a bit more readable and only does the calculation once.Is it possible to do something similar in SQL? I've included some sample data if anyone wants to try it out.if exists (select * from dbo.sysobjects where id = object_id(N'[MedianT]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [MedianT]GO CREATE TABLE MedianT (_TIMESTAMP DATETIME, _VALUE int) INSERT INTO MedianT (_TIMESTAMP, _VALUE)SELECT '4/29/1962', 0 UNIONSELECT '5/1/1962', 5 UNIONSELECT '5/3/1962', 8 UNIONSELECT '5/4/1962', 11 UNIONSELECT '5/8/1962', 11 UNIONSELECT '5/10/1962', 14 UNIONSELECT '5/13/1962', 0 UNIONSELECT '5/14/1962', 4 UNIONSELECT '5/29/1962', 7 UNIONSELECT '5/29/1963', 7 UNIONSELECT '5/29/1967', 9 UNIONSELECT '5/29/1969', 3 UNIONSELECT '5/29/1974', 5 UNIONSELECT '5/29/1980', 8 UNIONSELECT '5/29/2000', 10 SELECT _TIMESTAMP, _VALUE, -- Now get the increase in count since the previous record. -- If this record value < prev record value then return this record value. Increase = CASE WHEN -- First occurrance of repeating query _VALUE - ( SELECT _VALUE FROM MedianT T WHERE T._TIMESTAMP = (SELECT -- MAX(_TIMESTAMP) FROM MedianT T2 WHERE T2._TIMESTAMP < MedianT._TIMESTAMP ) ) >= 0 THEN -- First occurrance of repeating query _VALUE - ( SELECT _VALUE FROM MedianT T WHERE T._TIMESTAMP = (SELECT -- MAX(_TIMESTAMP) FROM MedianT T2 WHERE T2._TIMESTAMP < MedianT._TIMESTAMP ) ) ELSE _VALUE ENDFROM MedianT
Many thanks.