tags:

views:

73

answers:

3

I have a query, Im trying to select the maximum value from the summer period (nov-april down here) but it only gives me values from nov-dec with this query. Any ideas why?

SELECT TOP 10 Value, DateTime 
  FROM history
 WHERE Tagname = @Tag
   AND 
       ((DateTime >= @StartYear AND DateTime < @StartWinter)
    OR 
       (DateTime >= @FinishWinter AND DateTime < @FinishYear))
ORDER BY Value DESC
A: 

(DateTime >= startYear AND datetime < startwinter) gives you all results between jan and april 2009. (Datetime > finishwinter and datetime < finishyear) gives all results in nov dec 09.

So, you're selecting top 10 from Jan Feb March April Nov Dec 2009. If that's what you want to select from, and you're only getting values in Nov Dec 2009, check to see that there should be values in the other months?

If @startwinter isn't year-sensitive you might also get jan-apr 2010.

Dire
I have checked the data, and I should be getting results from both periods. If I swap the two clauses around, I get only data from jan-apr. Its as if that line is being completely ignored...
HamishC
If, for example, you have a bunch of high values that are the same for each of the two periods you're selecting, then you may well get the results you're seeing. Say, just for example, that 1000 was the highest Value in your table, and that there were twenty results with Value = 1000, ten in jan-apr, and ten in nov-dec. You could validly get any ten of those ten as your results, and which ten you get back will depend on how you construct the query.See if you get the same result set back if you use `ORDER BY Value DESC, DateTime`. That might give you a clue.
Matt Gibson
Nope thats not the case either, I have been using two seperate queries to get the data, and more often than not the values are all unique (peak current through a substation circuit breaker). I was just curious as to why this doesnt work.
HamishC
A: 

Shouldn't you use a 'ORDER BY' when using 'TOP 10'?

And what locale do you live in, or, to rephrase it: what are reasonable dates for (@StartYear, @StartWinter, @FinishWinter, @FinishYear)

In Europe I expect:

  • StartYear = 2010-01-01
  • FinishYear= 2010-12-31
  • StartWinter=2010-12-20 (about)
  • FinishWinter=2010-03-20 (about)

So the first period would go from 2010-01-01 to 2010-12-20 (about) and the second from March 2010 to End of year.

So this would include the whole year, and most of it, from 03.20 to 12.20 double.

user unknown
erm there is an 'ORDER BY Value DESC' on the end. The dates are mentioned above too, Im down in NZ so jan01, may01, nov01, (2009) jan01 (2010).
HamishC
A: 

Hey thanks for the help everyone, it seems this is a problem with our historian (a linked db from sql server) so Ill take the issue up with them. I tried the query on a regular mssql db and it seeems fine...

HamishC