我有一个表HO_TRAN,其中存储了关于事务的5年数据。 table由Season_id,farmer_id,plot_no,Net_weight等字段组成。 季节ID是交易年份 farmer_id是消费者ID Plot_no是农民的独特编号。 net_weight是农民通过他的各种情节向我们提供的产品。
我需要的是通过farmer_id分析(比较)2年数据,意味着我想过滤提供了年份和不提供年份的farmer_id。我很困惑如何为此设计SQL查询。我希望以这种方式输出
Farmer_id | Plot_no | Net_weight
1 | 123 | 5.00
| 321 | 15.00
2 | 456 | 6.00
| 159 | 65.00
| 187 | 56.00
3 | 642 | 47.00
答案 0 :(得分:0)
假设您有两年的时间,比如YEAR1和YEAR2,那么您可以使用分析函数来达到此目的:
select Farmer_id, Plot_no, Net_weight
from (select ht.*,
max(case when season = YEAR1 then 1 else 0 end) over (partition by farmer_id) as year1,
max(case when season = YEAR2 then 1 else 0 end) over (partition by farmer_id) as year2
from HO_TRAN ht
) ht
where year1 = 1 and year2 = 1
答案 1 :(得分:0)
select Farmer_id, Plot_no, Net_weight
from HO_TRAN as ht
where exists (
select 1 from HO_TRAN
where Farmer_id = ht.Farmer_id
and year between X and Y
group by Farmer_id
having count(distinct year) = 2
);
或类似的东西,取决于你的意思。你说你想要分析和比较多年,但你提出的结果中没有一年。