2017-11-30 3 views
0

私は2つのタイプの顧客であるRegular - Rと 'Corporate-C`を食料品店に持っていて、それらには日付に基づく価格の合意があるとします。サンプルデータは次のようになります。句による特定の注文Oracle

Type(C/R) CustID From Date Cost 
C     1/11/2017 10 
C    1 1/11/2017 12 
        1/11/2017 14 
R     1/11/2017 9 
C    1 10/11/2017 11 
C     11/11/2017 15 

表からはTypeCustidは必須ではありません見ることができます。私のレートピッカーは、日付からの入力から最大一致する列と一致し、適用するためのコストを与えます。

サンプル入力:(入力は常にタイプ、お客様IDと日付からになります)

Case 1: Type - c,Cust ID - 1, dealdate(fromdate) - 2/11/2017

出力:Row number 2 with price 12

Case 2: Type - C, Cust ID - 2,dealdate(fromdate) - 2/11/2017

出力:Row number 1 with price 10

Case 3: Type - C, Cust ID - 2,dealdate(fromdate) - 12/11/2017

出力:Row number 6 with price 15

私の出力は、最初の最大のマッチング列にマッチしますし、それが一致する列が日付からより高い優先度を持っている(しかし、はい、それは有効期間であることを有することを意味する有効な日付をチェックします)。

私のアプローチ:

select * from (
select row_number() over(partition by partition_column order by 
from_date desc,type,custid) rn,a.* from (
select *,'1' as partition_column from rate 
where from_date <= :d_date and (type = :type or type is null) and 
(custid = :custid or custid is null)) a) where rn=1; 

私は望ましい結果を得ていないのです。誰も助けてください。

+0

CUST ID = 2はあなたのサンプルデータに欠けていますか? – Ronnis

+0

cust id = 2がないことは意味しません。つまり、私はcust id 2と特別な契約を結んでいません。そして、行番号1は価格10で選択されます。ヌルは誰にでも使用できることを象徴しています。値はその特定の人のみを意味します。 thanks mate。 – Abhishek

答えて

1

あなたがしたいことを理解していると思います。

create table rate(
    type  varchar2(5) 
    ,cust_id number 
    ,from_date date not null 
    ,cost  number not null 
); 

insert into rate(type, cust_id, from_date, cost) values('C', null, date '2017-11-01', 10); 
insert into rate(type, cust_id, from_date, cost) values('C', 1, date '2017-11-01', 12); 
insert into rate(type, cust_id, from_date, cost) values(null, null, date '2017-11-01', 14); 
insert into rate(type, cust_id, from_date, cost) values('R', null, date '2017-11-01', 9); 
insert into rate(type, cust_id, from_date, cost) values('C', 1, date '2017-11-10', 11); 
insert into rate(type, cust_id, from_date, cost) values('C', null, date '2017-11-11', 15); 

このステートメントは、タイプまたは顧客のいずれかと一致するレコードを検索することによって機能します。日付入力が満たされている必要があります。最終的には、顧客IDより顧客IDよりも高い優先度が与えられ、複数のレコードが来た場合には、最新の日付からのものが選択されます。

select type, cust_id, cost, from_date 
    from (select r.* 
       ,case when cust_id = 2 then 1 end as cust_id_matches 
       ,case when type = 'C' then 1 end as type_matches 
      from rate r 
     where (type = 'C' or cust_id = 2)  -- Either attribute my match 
      and from_date <= date '2017-11-12' -- Mandatory, must be valid 
     order 
      by cust_id_matches asc nulls last -- Order customer ID matches first 
       ,type_matches asc nulls last -- Then Matches for type 
       ,from_date  desc    -- Pick most recent if multiple records 
     )   
where rownum = 1;   

Here is a SQL Fiddle

+0

これは私が今必要だったものです。 – Abhishek

関連する問題