在相同的表中查找不同列的匹配记录

时间:2016-01-27 19:07:27

标签: tsql sql-server-2012

我有这个问题:

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变为每个Locatn_K的&lt;&gt; AMP的次数,其中MTR_INST_D = MTR_XCHG_OUT_D。例如,LOCATN_K = 85420005从AMP到EEM,MTR_XCHG_D = MTR_INST_D 1次(日期是&#39; 2014-08-27&#39;。LOCATN_K 85430001从AMP到EEM在日期&#39; 2015- 01-05&#39;和&#39; 2016-01-12。

请帮我一些T-SQL来回答这个问题!

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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;#39;到&amp;#&amp;和&amp;&amp;&#39; Amp&#39;对于&amp; amp;&#39;但是我想要得到的是&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&#39; Amp&#39;。

对我来说,最简单的方法是:

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