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回日付をチェックしていますが、これは何とか1回できる気がしますか? 現在、合計列で 1 回だけチェックすると、colorgreen + colorred は、日付に関係なくカウントされるため、合計よりも大きくなる可能性があります。

クエリを何らかの方法で強化できますか?

4

2 に答える 2

2

you can simplify like this. but PLEASE check your SQL. you're mixing TO_DATE and CHAR datatypes. this will only end in disaster.

eg you have:

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

in one case you are TO_DATE'ing ad_startdate but not another (so is it a date already or not?). you are also TO_DATEing the column but crucially WITHOUT a format mask. is the column really a VARCHAR datatype? if so you really should not store dates as anything but DATEs.

anyway assuming the column is a DATE datatype and the binds are of type 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
于 2012-11-06T08:22:55.617 に答える
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

編集: コメントで指摘されているように、このクエリは、指定された間隔でオファーの日付を持たない ID を除外します。

于 2012-11-06T07:53:37.183 に答える