3

我有下表,它保存了一年中特定周的销售数据。

销售量

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 周之间的记录。

例如

  1. 2011 年第 50 周至 2012 年第 5 周之间
  2. 2012 年第 1 周至 2012 年第 6 周之间

由于在 SQL 方面的经验很少,我尝试了以下查询,该查询适用于案例 2,但不适用于案例 1。

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

据我了解,条件分组似乎不起作用。就好像没有条件分组一样。

4

4 回答 4

4
select *
from
(
   Select *, year*100 + week as yearweek
   from table
) v
where yearweek between 201150 and 201205
于 2012-08-29T08:34:00.327 回答
1

通过比较临时记录更简单、更快、更优雅:

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

这个密切相关的答案有更多详细信息,包括基准测试和一些更多可能的解决方案。

于 2012-08-29T23:52:20.457 回答
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)
于 2012-08-29T08:32:53.080 回答
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' )
于 2012-08-29T08:33:49.013 回答