表tariff_info, 原始数据:

sqlserver查询数据表中每个类别最新的一条记录-LMLPHP

想要的结果:以start_time时间倒序排序, 以code分类, 查询每一类最新的一条记录

sqlserver查询数据表中每个类别最新的一条记录-LMLPHP

sql:

SELECT
a.*
FROM
TARIFF_INFO a,
(
SELECT
code,
MAX (start_time) start_time
FROM
TARIFF_INFO
GROUP BY
code
) b
WHERE
a.start_time = b.start_time
AND a.code = b.code
ORDER BY
a.code

这样查询结果已经实现了, 但是需要添加过滤条件, 即当前时间在start_time和end_time之间.  如果还用上面的sql仅仅在末尾追加一个条件发现查询结果为空:

sqlserver查询数据表中每个类别最新的一条记录-LMLPHP

所以必须在子查询中添加同样的过滤条件方可查出正确结果, 如下面sql:

SELECT
a.*
FROM
TARIFF_INFO a,
(
SELECT
code,
MAX (start_time) start_time
FROM
TARIFF_INFO
WHERE
start_time <= '2018-09-18'
GROUP BY
code
) b
WHERE
a.start_time = b.start_time
AND a.code = b.code
AND a.start_time <= '2018-09-18'
ORDER BY
a.code

sqlserver查询数据表中每个类别最新的一条记录-LMLPHP

另:需要注意sql中时间区间的比较<=貌似有临界日期会漏掉的情况, 这里不作赘述了.以下sql和上面的异曲同工:

SELECT
a.*
FROM
TARIFF_INFO a
INNER JOIN (
SELECT
code,
MAX (start_time) 'start_time'
FROM
TARIFF_INFO
WHERE CONVERT(VARCHAR(10),start_time,121) <= '2018-09-18'
GROUP BY
code
) b ON a.code = b.code
AND a.start_time = b.start_time
AND CONVERT(VARCHAR(10),b.start_time,121) <= '2018-09-18'
ORDER BY
a.code

感谢:https://blog.csdn.net/sinat_27693393/article/details/78673971

05-11 22:16
查看更多