2014-07-21 57 views
0

我有我認爲是一個常見的問題,但我已經搜索並找不到答案。選擇已更改的記錄

我有一個包含(簡體)月,項目類型一大桌,價值

Jan ProjectA X 15000, 
Jan ProjectB X 2000, 
Jan ProjectB Y 2000, 
Jan ProjectC X 3000, 
..... 
Feb ProjectA X 15000, 
Feb ProjectB Y 4000, 
Feb ProjectC X 3000, 
Feb ProjectD X 8989, 
..... 
Mar ProjectA X 15000, 
Mar ProjectB Y 4000, 
Mar ProjectC X 3000, 
Mar ProjectD X 8989, 
..... 

我需要一個查詢,顯示:

所有項目+型一月,但不是月和​​
所有項目+鍵入2月但不是1月AND
所有項目+鍵入兩個值但具有不同的值

我需要它在任何兩個月之間抱歉不清楚

任何幫助將不勝感激(我曾嘗試與NOT IN子查詢和加入,但我覺得我失去了一些東西簡單,因爲我的查詢變得非常大,仍然沒有工作)

+1

這是與聚集做到這一點單個查詢'所有項目+鍵入1月但不是2月和 所有項目+鍵入2月但不是1月和 所有項目+鍵入兩個,但具有不同的值'? – bumbumpaw

+2

雖然他們沒有工作,但在sql中看到失敗的嘗試會很有幫助。 – paqogomez

+0

我的意思是它作爲一個單一的查詢。我將在下次發佈我的嘗試。謝謝。 – arbit

回答

2

你應該能夠

select project, type, 
     (case when sum(case when month = 'jan' then 1 else 0 end) > 0 and 
        sum(case when month = 'feb' then 1 else 0 end) = 0 
      then 'Jan-Only' 
      when sum(case when month = 'jan' then 1 else 0 end) = 0 and 
        sum(case when month = 'feb' then 1 else 0 end) > 0 
      then 'Feb-Only' 
      when max(case when month = 'jan' then value else 0 end) <> 
        max(case when month = 'feb' then value else 0 end) 
      then 'Different' 
     end) as Which 
from largetable lt 
group by project, type; 

可能過濾掉其中的值相等 - 2月是使用子查詢的那些最簡單的方法:

select t.* 
from (select project, type, 
      (case when sum(case when month = 'jan' then 1 else 0 end) > 0 and 
         sum(case when month = 'feb' then 1 else 0 end) = 0 
        then 'Jan-Only' 
        when sum(case when month = 'jan' then 1 else 0 end) = 0 and 
         sum(case when month = 'feb' then 1 else 0 end) > 0 
        then 'Feb-Only' 
        when max(case when month = 'jan' then value else 0 end) <> 
         max(case when month = 'feb' then value else 0 end) 
        then 'Different' 
       end) as Which 
     from largetable lt 
     where month in ('jan', 'feb') 
     group by project, type 
    ) t 
where Which is not null; 
+0

我希望的簡單解決方案就在那裏 - 儘管我永遠不會找到它 - 謝謝 - 它的功能非常好 – arbit