我有以下表格,可以保存一年中特定周的销售数据。
销售
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
我想找到第1年第1周和第2年第2周之间的记录。
例如
在sQL方面经验不多,我尝试了以下查询,该查询适用于案例2但不适用于案例1。
SELECT * from sales WHERE (week >= 1 AND year >= 2012) AND (week <= 6 AND year <= 2012 )
根据我的理解,看起来条件分组不起作用。这就好像没有任何条件组合。
答案 0 :(得分:4)
select *
from
(
Select *, year*100 + week as yearweek
from table
) v
where yearweek between 201150 and 201205
答案 1 :(得分:1)
通过比较临时记录,更简单,更快速,更优雅:
SELECT *
FROM tbl
WHERE (year, week) BETWEEN (2011, 50) AND (2012, 5);
此closely related answer的更多细节,包括基准测试,以及更多可能的解决方案。
答案 2 :(得分:0)
此查询适用于案例1:
SELECT * from sales WHERE (week >= 50 AND year = 2011) OR (week <= 5 AND year = 2012 )
虽然这应适用于大多数相邻年份的案例(例如2011年和2012年或其他任何情况,但不是2001年至2010年)。这种情况有点复杂,但仍然相当简单。
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 )
好的,这是更大范围的例子。
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)
答案 3 :(得分:0)
尝试第一个例子
SELECT *
FROM sales
WHERE (year = 2011 AND week > 50)
OR (year = 2012 AND week < 5)
一般
SELECT *
FROM sales
WHERE (year = 'year1' AND week > 'week1')
OR (year > 'year1' AND year < 'year2' )
OR (year = 'year2' AND week < 'week2' )