我当前的数据:
Month Price A Price B Status Approval
January 1000 2000 1 0
February 1000 2000 1 0
March 1000 2000 1 0
April 1000 2000 1 0
May 1000 2000 1 0
June 1000 2000 1 0
July 1000 2000 1 0
August 1000 2000 1 0
September 1000 2000 1 0
October 1000 3000 1 0
October 2000 2000 2 0
October 3000 2000 2 1
November 1000 2000 1 0
December 1000 2000 1 0
*Status 1 = Not Changed, Status 2 = Changed, Approval 1 = Approved
当月> 1(我的情况是十月)时,我要显示的是
,
如果STATUS = 2 AND APPROVAL = 1
不存在,
显示数据 STATUS = 1 AND APPROVAL = 0
其他显示STATUS = 2 AND APPROVAL = 1
使用分组依据,
不起作用,如果再过一个月,它将显示第一个数据 比1
我的查询:
SELECT A.NAME AS MONTH,
IFNULL( B.PRICE_A, 0 ) PRICE_A,
IFNULL( B.PRICE_B, 0 ) PRICE_B,
STATUS,
APPROVAL,
FROM
REF_MONTH A
LEFT OUTER JOIN (
SELECT
SUBSTR( PERIOD, '5,2' ) MONTH,
ROUND( PRICE_A_FIX, 2 ) PRICE_A,
ROUND( PRICE_B_FIX, 2 ) PRICE_B,
A.STATUS,
A.APPROVAL,
FROM
PRICE_MONTH_LIST A
WHERE
SUBSTR( PERIOD, 1, 4 ) = 2018
) B ON B.MONRH= A.MONTH
WHERE DATE_FORMAT( STR_TO_DATE( CONCAT( 2018, month), '%Y%m' ), '%Y%m' ) <=
DATE_FORMAT( SYSDATE( ), '%Y%m' )
GROUP BY A.MONTH
ORDER BY A.ID;
我的预期结果:
Month Price A Price B Status Approval
January 1000 2000 1 0
February 1000 2000 1 0
March 1000 2000 1 0
April 1000 2000 1 0
May 1000 2000 1 0
June 1000 2000 1 0
July 1000 2000 1 0
August 1000 2000 1 0
September 1000 2000 1 0
October 3000 2000 2 1
November 1000 2000 1 0
December 1000 2000 1 0
答案 0 :(得分:0)
下面是查询-
with table1 as
(
select 'January' as month, 1000 as priceA, 2000 as priceB, 1 as status, 0 as approval from dual
union all
select 'October' as month, 1000 as priceA, 3000 as priceB, 1 as status, 0 as approval from dual
union all
select 'October' as month, 2000 as priceA, 2000 as priceB, 2 as status, 0 as approval from dual
union all
select 'October' as month, 3000 as priceA, 2000 as priceB, 2 as status, 1 as approval from dual
)
,t1 as
(
select month, count(*) as cnt, min(status) as min_status,
max(status) max_status, min(approval) min_app, max(approval) max_app from table1
group by month
)
,t2 as
(
select
month,
case when cnt>1 and max_status<>2 and max_app<>1 then min_status else max_status end as status1,
case when cnt>1 and max_status<>2 and max_app<>1 then min_app else max_app end as approval1
from t1
)
select
t.month,
t.priceA,
t.priceB,
t.status,
t.approval
from table1 t
inner join t2 on t.month=t2.month and t.status=t2.status1 and t.approval=t2.approval1;
结果-
January 1000 2000 1 0
October 3000 2000 2 1
由于没有插入脚本,因此我将CTE与oralce数据库一起使用。
希望这会有所帮助。