I’m trying to query to only pull the most recent sale date but keep the unique value of “strap”. This is the query result I have.
nh_cd strap dor_cd acreage sqft sale date reception_num price asd_val rea_cd 178.00 R0000001 AG 4.7160 205443 2019-07-11 00:00:00.000 3723615 890000 200 05 178.00 R0000001 AG 4.7160 205443 2020-05-29 00:00:00.000 3787823 880000 200 40 205.00 R0022222 AGRES 5.8030 252771 2019-06-10 00:00:00.000 3718473 647500 520200 40
This is what I’ve built so far, but it doesn’t give me my desired result of a recent date.
SELECT distinct parcel.nh_cd ,sales.strap ,parcel.dor_cd ,detail.acreage ,detail.sqft ,max(sales.dos) ,sales.reception_num ,sales.price ,parcel.asd_val ,sales.rea_cd ,sales.qu_flg ,sales.valid_cd ,sales.vi ,site.str_num ,site.str_pfx ,site.str ,site.str_sfx ,site.city ,parcel.status_cd ,strap_idx.folio FROM detail INNER JOIN parcel ON parcel.strap = detail.strap INNER JOIN sales ON parcel.strap = sales.strap INNER JOIN site ON parcel.strap = site.strap INNER JOIN strap_idx ON parcel.strap = strap_idx.strap INNER JOIN lnd_a ON parcel.strap = lnd_a.strap WHERE lnd_a.st_use_cd IN ('4117','4127','4137','4147','4167','4177','4180') AND parcel.dor_cd LIKE 'AG%' AND parcel.status_cd = 'A' AND (sales.price > '0') AND (site.ln_num = '1') AND (sales.dos>='07/01/2018') AND (sales.dos<='08/24/2020') GROUP by parcel.nh_cd ,sales.strap ,parcel.dor_cd ,detail.acreage ,detail.sqft ,sales.dos ,sales.reception_num ,sales.price ,parcel.asd_val ,sales.rea_cd ,sales.qu_flg ,sales.valid_cd ,sales.vi ,site.str_num ,site.str_pfx ,site.str ,site.str_sfx ,site.city ,parcel.status_cd ,strap_idx.folio
This is the result I want
nh_cd strap dor_cd acreage sqft sale date reception_num price asd_val rea_cd 178.00 R0000001 AG 4.7160 205443 2020-05-29 00:00:00.000 3787823 880000 200 40 205.00 R0022222 AGRES 5.8030 252771 2019-06-10 00:00:00.000 3718473 647500 520200 40
How would I go about doing this?
Advertisement
Answer
You can ROW_NUMBER()
it
SELECT * FROM ( SELECT distinct parcel.nh_cd ,sales.strap ,parcel.dor_cd ,detail.acreage ,detail.sqft ,sales.dos ,sales.reception_num ,sales.price ,parcel.asd_val ,sales.rea_cd ,sales.qu_flg ,sales.valid_cd ,sales.vi ,site.str_num ,site.str_pfx ,site.str ,site.str_sfx ,site.city ,parcel.status_cd ,strap_idx.folio , ROW_NUMBER() OVER(PARTITION BY parcel.nh_cd, sales.strap ORDER BY sales.dos DESC) AS rn FROM detail INNER JOIN parcel ON parcel.strap = detail.strap INNER JOIN sales ON parcel.strap = sales.strap INNER JOIN site ON parcel.strap = site.strap INNER JOIN strap_idx ON parcel.strap = strap_idx.strap INNER JOIN lnd_a ON parcel.strap = lnd_a.strap WHERE lnd_a.st_use_cd IN ('4117','4127','4137','4147','4167','4177','4180') AND parcel.dor_cd LIKE 'AG%' AND parcel.status_cd = 'A' AND (sales.price > '0') AND (site.ln_num = '1') AND (sales.dos>='07/01/2018') AND (sales.dos<='08/24/2020') ) t WHERE rn = 1