2012-11-06 74 views
1

我有以下查詢:一個日期檢查整個查詢

select 
    fp.id, 
    fr.id, 
    sum(case 
     when to_date(fp.offered_date) BETWEEN TO_DATE(:ad_startdate, 'YYYY-MM-DD') 
      AND TO_DATE(:ad_enddate, 'YYYY-MM-DD') and fp.result <> 'E' 
      then 1 
     else 0 
     end) total, 
    sum(case when fp.result = 'G' 
     and to_date(fp.offered_date) >= :ad_startdate 
     and to_date(fp.offered_date) <= :ad_enddate then 1 else 0 end) colorgreen, 
    sum(case when fp.resultat = 'R' 
     and to_date(fp.offered_date) >= :ad_startdate 
     and to_date(fp.offered_date) <= :ad_enddate then 1 else 0 end) colorred 
FROM 
    fruit_properties fp, fruit fr 
WHERE 
    fp.id = fr.id 
GROUP BY 
    fp.id, fr.id 

我檢查日期1次次金額列,並有此可一次不知何故的感覺?現在,如果我只在總列中檢查一次,那麼colorgreen + colorred可能會比總數大,因爲無論它們具有哪個日期,它都會計數。

我的查詢可以以某種方式增強嗎?

回答

2

你可以這樣簡化。但請檢查你的SQL。你在混合TO_DATE和CHAR數據類型。這隻會在災難中結束。

如您有:

when to_date(fp.offered_date) BETWEEN TO_DATE(:ad_startdate, 'YYYY-MM-DD') 
      AND TO_DATE(:ad_enddate, 'YYYY-MM-DD') 

VS

sum(case when fp.result = 'G' 
    and to_date(fp.offered_date) >= :ad_startdate 

在一種情況下,你都TO_DATE'ing ad_startdate而不是另一個(所以它是一個日期已經或沒有?)。你也是TO_DATEing列,但關鍵沒有格式掩碼。該列是否真的是VARCHAR數據類型?如果是這樣的話,你真的不應該將日期存儲爲日期而不是日期。

反正假設列是一個DATE數據類型和結合是DATE類型..

select fruit_prop_Id,fruit_id, 
     sum(case when result != 'E' then within_offer else 0 end) total, 
     sum(case when result = 'R' then within_offer else 0 end) colorred, 
     sum(case when result = 'G' then within_offer else 0 end) colorgreen 
from (select fp.id fruit_id, 
       fr.id fruit_prop_Id, 
       fp.result, 
       case 
        when fp.offered_date >= :ad_startdate 
        and fp.offered_date <= :ad_enddate then 1 else 0 end within_offer 
     from fruit_properties fp, fruit fr 
     where fp.id = fr.id) 
     group by fruit_id, fruit_prop_Id 
+0

是的,你是對的,我很新的SQL,這是一個馬虎做一個。其實查詢已經是一個嵌套選擇,我希望避免另一個。什麼會提供最好的性能,我的解決方案與2選擇或你的日期檢查更好,但與3? –

+0

雖然客戶端使用這個特定的SQL確保它是一個日期輸入:) –

+0

不要害怕嵌套選擇。他們不(必然)暗示更糟的表現(它只是一個觀點)。 oracle可以並且會在內部重寫查詢。你會發現嵌套select與原始查詢一樣。 – DazzaL

1

你可以把日期檢查在where子句中:

select 
    fp.id, 
    fr.id, 
    sum(case when and fp.result <> 'E' then 1 else 0 end) total, 
    sum(case when fp.result = 'G' then 1 else 0 end) colorgreen, 
    sum(case when fp.resultat = 'R' then 1 else 0 end) colorred 
FROM 
    fruit_properties fp, fruit fr 
WHERE 
    fp.id = fr.id 
    AND to_date(fp.offered_date) >= :ad_startdate 
    AND to_date(fp.offered_date) <= :ad_enddate 
GROUP BY 
    fp.id, fr.id 

編輯:在評論中指出,該查詢會過濾掉不具有在給定的時間間隔任何要約日期標識。

+0

爲你篩選出的行,這將改變他的回答。 – DazzaL

+0

即使你的答案幫助我,我不能應用它,因爲我不能過濾出日期,這會給我很壞的結果 –