3

I have following table which saves sales data for specific week of a year.

Sales

week | year | value
50   | 2011 | 150
51   | 2011 | 151
52   | 2011 | 152
1    | 2012 | 170
2    | 2012 | 190
3    | 2012 | 180
4    | 2012 | 160
5    | 2012 | 170
6    | 2012 | 290

I want to find records which lies between week1 of year1 and week2 of year2.

for example

  1. between week 50 of 2011 to week 5 of 2012
  2. between week 1 of 2012 to week 6 of 2012

Having little experience in sQL, I tried following query which works for case 2 but not for case 1.

SELECT * from sales WHERE (week >= 1 AND year >= 2012) AND (week <= 6 AND year <= 2012 ) 

Looks like grouping of condition does not work as I understand. It takes as if there are no grouping of conditions.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Amit Patel
  • 15,609
  • 18
  • 68
  • 106

4 Answers4

4
select *
from
(
   Select *, year*100 + week as yearweek
   from table
) v
where yearweek between 201150 and 201205
podiluska
  • 50,950
  • 7
  • 98
  • 104
1

Simpler, faster and more elegant with comparing ad-hoc records:

SELECT *
FROM   tbl
WHERE (year, week) BETWEEN (2011, 50) AND (2012, 5);

A lot more details at this closely related answer, including a benchmark, and some more possible solutions.

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
0

This query works for case 1:

SELECT * from sales WHERE (week >= 50 AND year = 2011) OR (week <= 5 AND year = 2012 )

Whereas this should work for most cases with adjacent years (e.g. 2011 and 2012 or whatever, but not 2001 to 2010). That case is a bit more complicated, but still fairly straightforward.

DECLARE @week1 INT
DECLARE @week2 INT
DECLARE @year1 INT
DECLARE @year2 INT

SELECT * from sales WHERE (week >= @week1 AND year = @year1) OR (week <= @week2 AND year = @year2 )

Okay, here is the example for a bigger range.

DECLARE @week1 INT
DECLARE @week2 INT
DECLARE @year1 INT
DECLARE @year2 INT

SELECT * from sales WHERE (week >= @week1 AND year = @year1) OR (week <= @week2 AND year = @year2 ) OR (year > @year1 AND year < @year2)
-- This last one gives ALL weeks for the full years between year1 and year2 (e.g. all weeks for 2002-2009 if we choose dates between 2001 and 2010)
Tom Chantler
  • 14,753
  • 4
  • 48
  • 53
0

Try this for 1st example

    SELECT * 
    FROM sales 
    WHERE (year = 2011 AND week > 50) 
       OR (year = 2012 AND week < 5)

In General

    SELECT * 
    FROM sales 
    WHERE (year = 'year1' AND week > 'week1') 
       OR  (year > 'year1' AND year < 'year2' ) 
       OR (year = 'year2' AND week < 'week2' )
hgulyan
  • 8,099
  • 8
  • 50
  • 75