編輯:下面是我正在使用的數據。我寫的查詢給出了基於OCCPSTAT字段的重複數據(最右邊的數據列,C或N)。需要幫助撰寫查詢。
我需要一個查詢來拉出最接近我定義日期的記錄(代碼是這樣),但是,如果有記錄的C和N副本,我只需要N記錄。
5000 1000 D001 RNT 100 11/1/2014 0:00 C
5000 1000 D001 GAS 200 11/1/2014 0:00 C
5000 1000 D001 ELC 300 11/1/2014 0:00 C
5000 1000 D001 WAT 400 11/1/2014 0:00 C
5000 1000 D001 TAX 500 11/1/2014 0:00 C
5000 1000 D001 INS 600 11/1/2014 0:00 C
5000 1000 D001 RNT 200 11/1/2015 0:00 C
5000 1000 D001 GAS 300 11/1/2015 0:00 C
5000 1000 D001 ELC 400 11/1/2015 0:00 C
5000 1000 D001 WAT 500 11/1/2015 0:00 C
5000 1000 D001 TAX 600 11/1/2015 0:00 C
5000 1000 D001 INS 700 11/1/2015 0:00 C
5000 1000 D001 RNT 300 11/1/2016 0:00 C
5000 1000 D001 GAS 400 11/1/2016 0:00 C
5000 1000 D001 ELC 500 11/1/2016 0:00 C
5000 1000 D001 WAT 600 11/1/2016 0:00 C
5000 1000 D001 TAX 700 11/1/2016 0:00 C
5000 1000 D001 INS 800 11/1/2016 0:00 C
5000 1000 D001 RNT 500 11/1/2017 0:00 C
5000 1000 D001 GAS 600 11/1/2017 0:00 C
5000 1000 D001 ELC 700 11/1/2017 0:00 C
5000 1000 D001 WAT 800 11/1/2017 0:00 C
5000 1000 D001 TAX 900 11/1/2017 0:00 C
5000 1000 D001 INS 100011/1/2017 0:00 C
5000 1000 D001 RNT 100 11/1/2014 0:00 N
5000 1000 D001 GAS 200 11/1/2014 0:00 N
5000 1000 D001 ELC 300 11/1/2014 0:00 N
5000 1000 D001 WAT 400 11/1/2014 0:00 N
5000 1000 D001 TAX 500 11/1/2014 0:00 N
5000 1000 D001 INS 600 11/1/2014 0:00 N
5000 1000 D001 RNT 200 11/1/2015 0:00 N
5000 1000 D001 GAS 300 11/1/2015 0:00 N
5000 1000 D001 ELC 400 11/1/2015 0:00 N
5000 1000 D001 WAT 500 11/1/2015 0:00 N
5000 1000 D001 TAX 600 11/1/2015 0:00 N
5000 1000 D001 INS 700 11/1/2015 0:00 N
5000 1000 D001 RNT 300 11/1/2016 0:00 N
5000 1000 D001 GAS 400 11/1/2016 0:00 N
5000 1000 D001 ELC 500 11/1/2016 0:00 N
5000 1000 D001 WAT 600 11/1/2016 0:00 N
5000 1000 D001 TAX 700 11/1/2016 0:00 N
5000 1000 D001 INS 800 11/1/2016 0:00 N
5000 1000 D001 RNT 500 11/1/2017 0:00 N
5000 1000 D001 GAS 600 11/1/2017 0:00 N
5000 1000 D001 ELC 700 11/1/2017 0:00 N
5000 1000 D001 WAT 800 11/1/2017 0:00 N
5000 1000 D001 TAX 900 11/1/2017 0:00 N
5000 1000 D001 INS 1000 11/1/2017 0:00 N
查詢是:
SELECT
BLDGID,
LEASID,
SUITID,
INCCAT,
AMOUNT,
EFFDATE,
OCCPSTAT
FROM(
SELECT
CM.BLDGID,
CM.LEASID,
LS.SUITID,
CM.INCCAT,
CM.AMOUNT,
CM.EFFDATE,
LS.OCCPSTAT,
ROW_NUMBER() OVER(PARTITION BY CM.BLDGID, CM.LEASID, LS.SUITID, CM.INCCAT, LS.OCCPSTAT
ORDER BY CM.EFFDATE DESC) AS rowno
FROM SQLDATA.DBO.CMRECC CM INNER JOIN SQLDATA.DBO.LEAS LS ON CM.LEASID = LS.LEASID
WHERE (CM.EFFDATE < '20170601') AND (CM.BLDGID = '85000') AND (LS.OCCPSTAT = 'C' OR LS.OCCPSTAT = 'N')
) AS d
WHERE rowno = 1
因爲案件正在同一行你不能用'Case'做,但你要檢查的結果集,並看到,如果相同的記錄存在與C和N然後只返回N,對嗎? – RezaRahmati
@RezaRahmati,這正是我想要做的。 – SQLISHARD