我有一个名称为Events
的SQL Server 2008数据库。我只想从RadioNumber
中获取所有最后一个条目。
我的SQL如下:
SELECT
MAX(timestamp) AS TimeStamp,
RadioNumber,
info,
RadioNumberInfo,
success
FROM
(SELECT TOP 100 PERCENT *
FROM Events
WHERE Type = 1
AND (Info IN (SELECT '1 Frei Funk' FROM Events)
OR Info IN (SELECT '2 Frei Wache' FROM Events)
OR Info IN (SELECT '3 Ausgerückt' FROM Events)
OR Info IN (SELECT '5 Sprechwunsch' FROM Events)
OR Info IN (SELECT '7 Patient aufg' FROM Events)
OR Info IN (SELECT '8 Am Transportziel' FROM Events))) AS tmp
GROUP BY
tmp.RadioNumber, tmp.Info, tmp.RadioNumberInfo, tmp.Success
ORDER BY
Timestamp DESC
结果看起来像这样,红色框的行是我要显示的行。
为了显示它们,我必须改变什么?
答案 0 :(得分:1)
最简单的方法可能是:
select top (1) with ties . . .
. . .
order by row_number() over (partition by tmp.RadioNumber order by Max(timestamp));
答案 1 :(得分:0)
您可以使用相关子查询
SELECT timestamp AS TimeStamp,
RadioNumber,
info,
RadioNumberInfo,
success
FROM (SELECT TOP 100 PERCENT *
FROM Events
WHERE Type = 1
AND ( Info IN (SELECT '1 Frei Funk'
FROM Events)
OR Info IN (SELECT '2 Frei Wache'
FROM Events)
OR Info IN (SELECT '3 Ausgerückt'
FROM Events)
OR Info IN (SELECT '5 Sprechwunsch'
FROM Events)
OR Info IN (SELECT '7 Patient aufg'
FROM Events)
OR Info IN (SELECT '8 Am Transportziel'
FROM Events) )) AS tmp
where timestamp in (select max(timestamp) from
FROM Events
WHERE Type = 1
AND ( Info IN (SELECT '1 Frei Funk'
FROM Events)
OR Info IN (SELECT '2 Frei Wache'
FROM Events)
OR Info IN (SELECT '3 Ausgerückt'
FROM Events)
OR Info IN (SELECT '5 Sprechwunsch'
FROM Events)
OR Info IN (SELECT '7 Patient aufg'
FROM Events)
OR Info IN (SELECT '8 Am Transportziel'
FROM Events) )) tmp1 where radionumber=tmp1.radionumber)
答案 2 :(得分:0)
感谢您的所有投入和帮助。我发现使用join会有一点帮助。
SELECT a.*
FROM Events AS a
INNER JOIN (
SELECT MAX(a.ID) AS ID, MAX(a.TimeStamp) AS TimeStamp, a.RadioNumber
FROM Events AS a
WHERE a.Type = 1
AND a.Info IN ('1 Frei Funk','2 Frei Wache','3 Ausgerückt','5 Sprechwunsch','7 Patient aufg','8 Am Transportziel')
GROUP BY a.RadioNumber
) AS b ON b.ID = a.ID
ORDER BY b.TimeStamp DESC