2012-08-29 337 views
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 

我想找到它位於YEAR1的week1和YEAR2的week2之間的記錄。

例如

  1. 2011 50周比較,以2012
  2. 第5周2012第1周間至2012年

具有SQL經驗少6個星期,我試過以下查詢適用於案例2但不適用於案例1.

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

看起來像分組的co ndition不工作,據我所知。這需要好像沒有條件分組。

回答

4
select * 
from 
(
    Select *, year*100 + week as yearweek 
    from table 
) v 
where yearweek between 201150 and 201205 
+2

+1我有同樣的解決方案。好處在於,該聲明適用於兩種情況,而不必求助於容易出錯的'或'子句。缺點是該聲明不可靠。 –

+0

這與SQL完美結合。面臨的挑戰是如何將這個查詢映射到Rails的ActiveRecord查詢機制。 –

+0

@AmitPatel'find_by_sql',也許? – podiluska

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) 
+0

只是爲了解釋,我是這樣做的,所以它可以利用任何可能存在的指數。 –

0

嘗試此1例

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') 
+0

這個「(2011年和2011年)」從未如此 –

+0

檢查一般查詢。這只是第一例的一個例子。當然這是沒有意義的,如果有一年的差異 – hgulyan

1

更簡單,更快,更多地飄逸着比較特設記錄:

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

這個closely related answer有很多更多的細節,包括基準,以及一些更可能的解決方案。