我正在使用SQL Server Express 2014,我需要从一个表中提取少数(现在为3个)不同ID的最后一个记录。
到目前为止,我做到了,但根本没有。我正在使用
SELECT TOP 1 [TagItemId], [TagValue]
FROM [DB].[dbo].[Table]
where [TagItemId] like 'Random.Int1'
order by [TagTimestamp] desc
SELECT TOP 1 [TagItemId], [TagValue]
FROM [DB].[dbo].[Table]
where [TagItemId] like 'Random.Int2'
order by [TagTimestamp] desc
SELECT TOP 1 [TagItemId], [TagValue]
FROM [DB].[dbo].[Table]
where [TagItemId] like 'Random.Int3'
order by [TagTimestamp] desc
结果是我需要的,但不完全是。我需要在单个表中得到三个结果,如:
TagItemId TagValue
Random.Int1 55
Random.Int2 75
Random.Int3 23`
而不喜欢:
TagItemId TagValue
Random.Int1 55
TagItemId TagValue
Random.Int2 75
TagItemId TagValue
Random.Int3 23`
原因是我需要将数据用于图表。
致以最诚挚的问候和感谢!
答案 0 :(得分:1)
您可以使用Row_Number
执行此操作SELECT [TagItemId],
[TagValue]
FROM
(
SELECT [TagItemId],
[TagValue],
ROW_NUMBER() OVER (PARTITION BY [TagItemId] ORDER BY [TagTimestamp] DESC) Rn
FROM [DB].[dbo].[Table]
WHERE [TagItemId] IN ('Random.Int1','Random.Int2','Random.Int3')
) t
WHERE Rn = 1
答案 1 :(得分:1)
有几种方法可以实现这一目标:
SELECT
MT.TagItemID,
MT.TagValue
FROM
My_Table MT
INNER JOIN
(
SELECT TagItemID, MAX(TagTimestamp)
FROM My_Table
WHERE
MT.TagItemID IN ('Random.Int1', 'Random.Int2', 'Random.Int3')
GROUP BY TagItemID) SQ ON SQ.TagItemID = MT.TagItemID
WHERE
MT.TagItemID IN ('Random.Int1', 'Random.Int2', 'Random.Int3')
或者:
SELECT
MT.TagItemID,
MT.TagValue
FROM
My_Table MT
WHERE
MT.TagItemID IN ('Random.Int1', 'Random.Int2', 'Random.Int3') AND
NOT EXISTS (SELECT * FROM My_Table MT2 WHERE MT2.TagItemID = MT.TagItemID AND MT2.Timestamp > MT.Timestamp)
或者:
;WITH CTE_WithRowNums AS
(
SELECT
MT.TagItemID,
MT.TagValue,
ROW_NUMBER() OVER(PARTITION BY TagItemID ORDER BY Timestamp DESC) AS row_num
FROM
My_Table MT
)
SELECT
TagItemID,
TagValue
FROM
CTE_WithRowNums
WHERE
row_num = 1
答案 2 :(得分:0)
你能不能只做一个简单的UNION ALL
select * from
(SELECT TOP 1 [TagItemId], [TagValue]
FROM [DB].[dbo].[Table]
where [TagItemId] like 'Random.Int1'
order by [TagTimestamp] desc )
UNION ALL
select * from
(SELECT TOP 1 [TagItemId], [TagValue]
FROM [DB].[dbo].[Table]
where [TagItemId] like 'Random.Int2'
order by [TagTimestamp] desc )
UNION ALL
select * from
(SELECT TOP 1 [TagItemId], [TagValue]
FROM [DB].[dbo].[Table]
where [TagItemId] like 'Random.Int3'
order by [TagTimestamp] desc )
可能崩溃了,因为每个选择TOP都有一个order by,所以我将查询“包装”到select *中,这样每个子查询都可以保留自己的ORDER BY子句