2016-12-24 5 views
0

既存のレコードがN日より古いかどうかをチェックする方法でレコードをアップセットすることは可能ですか?そうであれば、新しいレコードを作成し、それ以外の場合は既存のレコードを更新してください。既存のレコードがN日より古い場合にのみ更新する

+0

。 –

+0

可能であれば、そのようなことを避けたいだけですが、クエリをつけること – Tarlen

+2

あなたの質問を編集して、問題のテーブル(主キーとインデックスの定義を含む)の 'create table'ステートメントを追加してください。いくつかのサンプルデータおよびそのサンプルデータに基づく予想される結果。 [_Formatted_](http://dba.stackexchange.com/help/formatting)**テキスト**お願い、[スクリーンショットなし](http://meta.stackoverflow.com/questions/285551/why-may-i) -not-upload-images-of-on-ask-a-question/285557#285557) –

答えて

1

純粋なSQLソリューションをご希望の場合は、以下の方法をお試しください。

サンプルデータ:

create table abcd(
    id serial, 
    name varchar(100), 
    value int, 
    created date 
); 

insert into abcd(name, value, created) values 
('name 1', 10, current_date - interval '10' day), 
( 'name 2', 55, current_date - interval '120' day); 

; 

select * from abcd; 

id |name |value |created | 
---|-------|------|-----------| 
1 |name 1 |10 |2016-12-14 | 
2 |name 2 |55 |2016-08-26 | 

クエリ:おそらくトリガーで

with records as (
    select *, 
      case when created >= current_date - interval '10' day 
       then 'UPDATE' else 'INSERT' end as what_to_do 
    from abcd 
), 
up_date as (
    update abcd set value = 1000 
    where id in (select id from records where what_to_do = 'UPDATE') 
    returning id 
), 
in_sert as (
    insert into abcd(name, value, created) 
    select name, 1000, current_date 
    from records where what_to_do = 'INSERT' 
    returning id 
) 
select * from up_date 
union all 
select * from in_sert 
; 

select * from abcd; 
id |name |value |created | 
---|-------|------|-----------| 
2 |name 2 |55 |2016-08-26 | 
1 |name 1 |1000 |2016-12-14 | 
3 |name 2 |1000 |2016-12-24 | 
関連する問題