选择分组依据的第2个到最后一个日期

时间:2013-11-19 02:36:25

标签: mysql sql join

我有以下查询,我希望可以获取第二个到最新日期的数据

SELECT mn.meter_name, m.meter_number, m.meter_location, r.rates_meter_rate,
       r.rates_meter_PPD, m.meter_ID, mt.metertracking_readend,                        
       mt.metertracking_conversion, mt.metertracking_periodend 
FROM db_meters m, db_meters_name mn, db_rates_meter r, db_meters_tracking mt 
WHERE m.ICP_ID = '227' AND m.meter_name_ID = mn.meter_name_ID 
   AND r.meter_ID = m.meter_ID AND r.contract_ID = '70' AND mt.meter_ID = m.meter_ID   
   AND metertracking_periodend = ( 
      SELECT max(metertracking_periodend) 
      FROM db_meters_tracking 
      WHERE meter_ID = mt.meter_ID 
      AND metertracking_periodend < (SELECT MAX(metertracking_periodend) 
          FROM db_meters_tracking) 
     GROUP BY meter_ID ) 
ORDER BY  metertracking_periodend

这输出以下内容:

meter_name  meter_number  meter_location   rates_meter_rate  rates_meter_PPD  meter_ID  metertracking_readend  metertracking_conversion  metertracking_periodend

Anytime     9011656:1     in front office  0.13870           10.000           15        73856                  0.0000                     2013-11-29
Anytime     9011656:2     in front office  0.13870           10.000           16        2899                   1.0000                     2013-11-29

但是我期待以下内容:

meter_name  meter_number  meter_location   rates_meter_rate  rates_meter_PPD  meter_ID  metertracking_readend  metertracking_conversion  metertracking_periodend

Anytime     9011656:1     in front office  0.13870           10.000           15        0                      0.0000                     2013-10-31
Anytime     9011656:2     in front office  0.13870           10.000           16        0                      1.0000                     2013-10-31

我附上了表格的屏幕截图enter image description here

我出错的任何想法?或者SQL查询实际上是什么来完成这个?非常感谢。

1 个答案:

答案 0 :(得分:1)

我会重写这样的查询(我没有测试过,但我认为这是正确的):

SELECT mn.meter_name, m.meter_number, m.meter_location, r.rates_meter_rate,
       r.rates_meter_PPD, m.meter_ID, mt.metertracking_readend,                        
       mt.metertracking_conversion, mt.metertracking_periodend 
FROM db_meters m INNER JOIN db_meters_name mn ON m.meter_name_ID = mn.meter_name_ID
     INNER JOIN db_rates_meter r ON r.meter_ID = m.meter_ID 
     INNER JOIN db_meters_tracking mt ON mt.meter_ID = m.meter_ID
WHERE m.ICP_ID = '227' AND r.contract_ID = '70' 
AND 2 = (SELECT count(DISTINCT a.metertracking_periodend)
     FROM db_meters_tracking a 
     WHERE a.meter_ID = r.meter_ID AND mt.metertracking_periodend <= a.metertracking_periodend)
ORDER BY m.meter_ID, metertracking_periodend

请参阅this post以供参考。

在旁注中,请使用INNER JOIN而不是FROM子句中的逗号分隔表。它现在被认为是一个标准