2016-01-27 141 views
0

我有這個疑問:查找同一個表的不同列匹配的記錄

SELECT 
    TLOCMTR.LOCATN_K, TLOCMTR.MTR_SRP_N, TLOCMTR.MTR_INST_D, 
    TLOCMTR.MTR_XCHG_OUT_D, RATE.RATE, TMTR.MTR_MFR_MOD_C, 
    TMTR.MTR_MFR_NM_CD 
FROM 
    TMTR 
RIGHT OUTER JOIN 
    TLOCMTR ON TMTR.MTR_SRP_N = TLOCMTR.MTR_SRP_N 
LEFT OUTER JOIN 
    RATE ON TLOCMTR.LOCATN_K = RATE.LOCATN_K 
WHERE 
    ((RATE.RATE >= 20) AND (RATE.RATE <= 29)) 
    AND TLOCMTR.MTR_INST_D >= '2014-01-01' 
ORDER BY 
    LOCATN_K, MTR_INST_D 

代碼結果:

enter image description here

我需要做的是計算的次數MTR_MFR_NM_CD數從AMP更改爲<> AMP per Locatn_K,其中MTR_INST_D = MTR_XCHG_OUT_D。例如,LOCATN_K = 85420005從AMP到EEM,MTR_XCHG_D = MTR_INST_D 1次(日期爲'2014-08-27')LOCATN_K 85430001在2015-01-05和2016- 01-12。

請幫助我做一些T-SQL來回答這個問題!

回答

0

這是要領

select * 
    from (select LOCATN_K, MTR_INST_D, MTR_MFR_NM_CD 
       , LEAD(MTR_MFR_NM_CD, 1,0) OVER (PARTITTION LOCATN_K BY ORDER BY MTR_INST_D) AS MTR_MFR_NM_CD_NEXT 
      from 
      ... 
     ) tt 
where MTR_MFR_NM_CD  = 'AMP' 
    and MTR_MFR_NM_CD_NEXT <> 'AMP' 
+0

林不熟悉的超前和滯後,但只是看着它。看起來我可以在where子句中使用它。只是在選擇條款? – niemoy

+0

@niemoy好的,我會更新 – Paparazzi

+0

謝謝@飛盤。我試過這個並做了一些修改,但是這並沒有給出正確的結果。我仍然有Amp到Amp和<> AMP到AMP。我只是在尋找從Amp到<> AMP的記錄。所以交換日期有一個AMP,安裝日期有<> amp。我最終分裂了桌子並重新加入,這給了我想要的結果。 – niemoy

0

我試着飛盤的代碼進行了以下修改,但並沒有得到確切的結果:

select * 
from (select TLOCMTR.LOCATN_K, TLOCMTR.MTR_SRP_N, TLOCMTR.MTR_INST_D, TLOCMTR.MTR_XCHG_OUT_D, TMTR.MTR_MFR_MOD_C, TMTR.MTR_MFR_NM_CD, 
LEAD(TMTR.MTR_MFR_NM_CD, 1,0) OVER (PARTITION BY TLOCMTR.LOCATN_K 
ORDER BY MTR_INST_D) AS MTR_MFR_NM_CD_NEXT 
FROM TMTR RIGHT OUTER JOIN TLOCMTR ON TMTR.MTR_SRP_N = TLOCMTR.MTR_SRP_N 
LEFT OUTER JOIN RATE ON TLOCMTR.LOCATN_K = RATE.LOCATN_K 
WHERE ((RATE.RATE >= 20) AND (RATE.RATE <= 29)) AND TLOCMTR.MTR_INST_D>='2014-01-01' AND TMTR.MTR_MFR_NM_CD = 'AMP'  
) tt 
where tt.MTR_MFR_NM_CD = 'AMP' 
and tt.MTR_MFR_NM_CD_NEXT <> 'AMP' 
order by tt.LOCATN_K 

這導致'Amp'變爲'Amp'並且'Amp'變爲'Amp',但是我想得到的是'Amp'to <>'Amp'。

爲我做的最簡單的方法是:

WITH A AS 
(SELECT TLOCMTR.LOCATN_K, TLOCMTR.MTR_SRP_N, TLOCMTR.MTR_XCHG_OUT_D, TMTR.MTR_MFR_MOD_C, TMTR.MTR_MFR_NM_CD 
FROM TMTR RIGHT OUTER JOIN TLOCMTR ON TMTR.MTR_SRP_N = TLOCMTR.MTR_SRP_N LEFT OUTER JOIN RATE ON TLOCMTR.LOCATN_K = RATE.LOCATN_K 
WHERE ((RATE.RATE >= 20) AND (RATE.RATE <= 29)) and TLOCMTR.MTR_INST_D>='2014-01-01' AND TMTR.MTR_MFR_NM_CD = 'AMP' 
), 
B AS(
SELECT TLOCMTR.LOCATN_K, TLOCMTR.MTR_SRP_N, TLOCMTR.MTR_INST_D, TMTR.MTR_MFR_MOD_C, TMTR.MTR_MFR_NM_CD 
FROM TMTR RIGHT OUTER JOIN TLOCMTR ON TMTR.MTR_SRP_N = TLOCMTR.MTR_SRP_N 
LEFT OUTER JOIN RATE ON TLOCMTR.LOCATN_K = RATE.LOCATN_K 
WHERE ((RATE.RATE >= 20) AND (RATE.RATE <= 29)) AND TLOCMTR.MTR_INST_D>='2014-01-01' AND TMTR.MTR_MFR_NM_CD <> 'AMP' 
) 

SELECT A.LOCATN_K, A.MTR_SRP_N AmpyMeter, B.MTR_SRP_N CreditMeter, B.MTR_INST_D EXCG_DT, A.MTR_MFR_MOD_C AMP_MODEL, B.MTR_MFR_MOD_C Credit_MODEL 
FROM A inner join B on A.MTR_XCHG_OUT_D = B.MTR_INST_D and A.LOCATN_K=B.LOCATN_K 
ORDER BY LOCATN_K 

我的最終結果是這樣的: enter image description here

相關問題