从指定月份中提取每条唯一记录的最新记录

时间:2014-03-21 21:54:15

标签: sql sql-server-2008

我试图在每个时间间隔内为每个序列号提取最新记录。

SELECT 
        r.partno,
        r.serialno,
        p.description,
        r.location,
        r.ac_registr,
        cd.code,
        cv.life_value,
        cv.readout_ref_type,
        cv.readout_ref_key,
        cv.readout_date,
        cv.delta_value,
        cv.counter_valueno_i
FROM rotables r
JOIN part p ON (p.partno = r.partno)
JOIN counter c ON (c.ref_key = r.psn)
JOIN counter_template ct ON (ct.counter_templateno_i = c.counter_templateno_i)
JOIN counter_definition cd ON (cd.counter_defno_i = ct.counter_defno_i)
JOIN counter_value cv ON (cv.counterno_i = c.counterno_i)
WHERE 
    r.partno = ’3066T90G02’ 
    AND cv.readout_ref_type = 'FL2L' 
    AND readout_date BETWEEN '2014-02-01' AND '2014-02-28'

我在考虑添加

AND readout_date_INT = (SELECT MAX(readout_date_INT) 
                        FROM counter_value 
                        WHERE readout_date BETWEEN '2014-02-01' AND '2014-02-28')

但这不起作用......

1 个答案:

答案 0 :(得分:0)

GROUP BYHAVING在这里按顺序排列:

group by DATEPART(mm, readout_date), (other group by fields)
having max(readout_date)