分组排序查第一第二的差值

select product_id,ABS(firstvalue-secondvalue)/secondvalue tmp 
from (
SELECT product_id,
		max(case fund_subject when 'first' then fund_net_value end) 'firstvalue',
		max(case fund_subject when 'second' then fund_net_value end) 'secondvalue'
FROM 
(
SELECT * FROM 
(
SELECT net1.product_id  , 'first' as fund_subject , net1.fund_net_value_date as net_value_date ,net1.fund_net_value

FROM pef_fund_net_value net1
where net1.fund_net_value_date = 
( 
	SELECT max(fund_net_value_date)_date from pef_fund_net_value 
		WHERE product_id = net1.product_id
		
)
) am
union 
SELECT * FROM 
(
SELECT a.product_id, 'second' as fund_subject , MAX(fund_net_value_date) as net_value_date , fund_net_value
FROM
(
SELECT net.* FROM pef_fund_net_value net LEFT JOIN 
(
SELECT product_id , max(fund_net_value_date) as maxdate FROM pef_fund_net_value
GROUP BY product_id
)net2
ON  net.fund_net_value_date = net2.maxdate and net2.product_id = net.product_id
where net2.maxdate is null
) a
GROUP BY a.product_id
) pm

ORDER by product_id ,net_value_date desc

) al
group by product_id
) a4
where ABS(a4.firstvalue-a4.secondvalue)/a4.secondvalue > 0.05
-- 000001 first second net_value_date

  

原文地址:https://www.cnblogs.com/yibao/p/15174156.html