2016-05-17 5 views
0

を設定し、私のテーブルです:のPostgres:目標に基づいて毎月の計算を調整するには、以下

practice_id | practice_name | practice_location | practice_monthly_revenue | practice_no_of_patients |  date 
-------------+-------------------+-------------------+--------------------------+-------------------------+--------------------- 
      6 | Practice Clinic 1 | Location1   |     10000 |      8 | 2016-01-12 00:00:00 
      7 | Practice Clinic 1 | Location1   |     12000 |      10 | 2016-02-12 00:00:00 
      8 | Practice Clinic 1 | Location1   |      8000 |      4 | 2016-03-12 00:00:00 
      9 | Practice Clinic 1 | Location1   |     15000 |      10 | 2016-04-12 00:00:00 
      10 | Practice Clinic 1 | Location1   |      7000 |      3 | 2016-05-12 00:00:00 
      11 | Practice Clinic 2 | Location2   |     15000 |      12 | 2016-01-13 00:00:00 
      12 | Practice Clinic 2 | Location2   |      9000 |      8 | 2016-02-13 00:00:00 
      13 | Practice Clinic 2 | Location2   |      5000 |      2 | 2016-03-03 00:00:00 
      14 | Practice Clinic 2 | Location2   |     12000 |      9 | 2016-04-13 00:00:00 
---------------------------------------------------------------------------------------------------------------------------------- 

私は毎月の目標対毎月の収入を得るために、クエリの下に焼成しています: -

「Monthly_Revenueは」参照
select [date:month], SUM(practice_monthly_revenue) as Monthly_Revenue, 100000/12 as Goals 
from practice_info 
where practice_name IN ('Practice Clinic 1') 
group by [date:month], practice_name 
ORDER BY [date:month] ASC 

Goalが生成されると予想される正確な収入であったのに対し、毎月正確な収入が得られました。

今度は目標が満たされていない場合は、来月の目標を調整するSQLクエリを書く問題があります。 など。 3月に発生した収益が月間目標である8k未満であれば、目標の残りの金額は次の月目標で調整する必要があります。

これをSQLクエリで実現することは可能でしょうか、それともSQLプロシージャを作成する必要がありますか?

EDIT: - dbがpostgresに属することを追加するのを忘れました。

+0

MySQLまたはPostgresqlまたはMS SQL Server? – jarlh

+0

そのPostgresqlデータベース。 – Villie

+0

目標を1ヶ月超過した場合、翌月の目標は減少しますか? –

答えて

0

目標はただ、目標と収益を比較するために、クエリでそれを統合する

with recursive goals(mon, val, rev) as 
(select min([pinf.date:month]) as mon /* Starting month */, 8000 as val /* Starting goal value */, pinf.practice_monthly_revenue as rev 
    from practice_info pinf 
    where pinf.practice_name IN ('Practice Clinic 1') 
union all 
select goals.mon + 1 as mon, 8000 + greatest(0, goals.val - goals.rev) as val, pinf.practice_monthly_revenue as rev 
    from practice_info pinf, goals 
    where goals.mon + 1 = [pinf.date:month] 
     and pinf.practice_name IN ('Practice Clinic 1') 
) 
select * from goals; 

としてカウントすることができます。あなたが望むものではないかもしれませんが、あなたが主なポイントを得ると信じています。

関連する問題