我有一个表,每秒都会更新一些值。我想要检索每分钟的最后一条记录。
我已尝试过此代码,但它会返回所有记录。
SELECT
t0.brandID, t0.brandName, t0.cdt, t0.udt, t0.brandstatus
FROM
brands t0
WHERE
t0.cdt BETWEEN '2013-11-15' and '2014-11-15'
GROUP BY
t0.brandID, t0.brandName, t0.cdt, t0.udt, t0.brandstatus,(datepart(minute, t0.cdt) / 1)
我的表结构是:
ID brandname cdt udt brandstatus addedby
1 khasim 2013-11-01 19:14:18.120 2013-11-15 19:14:18.123 1 1
2 khasim 2013-11-01 19:14:18.121 2013-11-15 19:14:18.123 1 1
3 khasim 2013-11-01 19:14:18.122 2013-11-15 19:14:18.123 1 1
4 khasim 2013-11-01 19:14:18.123 2013-11-15 19:14:18.123 1 1
5 khasim 2013-11-02 19:17:57.700 2013-11-15 19:17:57.700 1 2
6 tanveer 2013-11-03 19:18:05.947 2013-11-15 19:18:05.947 1 2
7 abcdef 2013-11-04 20:50:06.783 2013-11-15 20:50:06.787 1 4
预期结果是:
ID brandname cdt udt brandstatus addedby
4 khasim 2013-11-01 19:14:18.123 2013-11-15 19:14:18.123 1 1
5 khasim 2013-11-02 19:17:57.700 2013-11-15 19:17:57.700 1 2
6 tanveer 2013-11-03 19:18:05.947 2013-11-15 19:18:05.947 1 2
7 abcdef 2013-11-04 20:50:06.783 2013-11-15 20:50:06.787 1 4
答案 0 :(得分:3)
您可以使用以下查询:
SELECT ID, brandname, cdt, udt, brandstatus, addedby
FROM (
SELECT ID, brandname, cdt, udt, brandstatus, addedby,
ROW_NUMBER() OVER (PARTITION BY brandname,
CAST(udt AS DATE),
CONVERT(VARCHAR(5), udt, 114)
ORDER BY udt DESC) AS rn
FROM brands) AS t
WHERE t.rn = 1
这部分:
CONVERT(VARCHAR(5), udt, 114)
用于从udt
字段中提取小时和分钟。
答案 1 :(得分:2)
使用ROW_NUMBER
添加与PARTITION BY
结合的编号:
WITH Cte AS(
SELECT *,
rn = ROW_NUMBER() OVER(
PARTITION BY brandname, DATEADD(MINUTE, DATEDIFF(MINUTE, 0, cdt), 0)
ORDER BY cdt DESC
)
FROM tbl
)
SELECT
ID, brandname, cdt, udt, brandstatus, addedby
FROM Cte
WHERE rn = 1
ORDER BY Id
此:
DATEADD(MINUTE, DATEDIFF(MINUTE, 0, cdt), 0)
将cdt
向下舍入到最近的分钟,即2013-11-01 19:14:18.123
到2013-11-01 19:14:00.000
。
答案 2 :(得分:0)
尝试以下查询
SELECT t0.brandID, t0.brandName, t0.cdt, t0.udt, t0.brandstatus FROM brands t0 WHERE t0.cdt BETWEEN '2013-11-15' and '2014-11-15'
and t0.cdt in (select MAX(cdt) from brands group by (CONVERT(CHAR(16),cdt,120)));