我在表格中有以下数据:
id name alarmId alarmUnit alarmLevel
1 test voltage psu warning
2 test voltage psu ceasing
3 test voltage psu warning
4 test temp rcc warning
5 test temp rcc ceasing
我只想显示有关每个colums组的最新信息(alarmId,alarmUnit),因此结果应如下所示:
3 test voltage psu warning
5 test temp rcc ceasing
到目前为止我已经尝试过了:
SELECT MAX(id) as id,name,alarmId,alarmUnit,alarmLevel GROUP BY alarmId,alarmUnit;
选定的ID似乎没问题,但选定的行与它们不对应。你能帮帮我吗?
答案 0 :(得分:29)
在Oracle
,SQL Server 2005+
和PostgreSQL 8.4
:
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY alarmId, alarmUnit ORDER BY id DESC) AS rn
FROM mytable
) q
WHERE rn = 1
在MySQL
:
SELECT mi.*
FROM (
SELECT alarmId, alarmUnit, MAX(id) AS mid
FROM mytable
GROUP BY
alarmId, alarmUnit
) mo
JOIN mytable mi
ON mi.id = mo.mid
在PostgreSQL 8.3
及以下:
SELECT DISTINCT ON (alarmId, alarmUnit) *
FROM mytable
ORDER BY
alarmId, alarmUnit, id DESC
答案 1 :(得分:19)
如果要获取max的行,则可能需要子查询。类似的东西:
SELECT *
FROM YourTable
WHERE id IN (
SELECT MAX(id) FROM YourTable GROUP BY alarmId, alarmUnit
)
答案 2 :(得分:8)
尝试:
SELECT * FROM table WHERE id IN
(SELECT MAX(id) FROM table GROUP BY alarmId, alarmUnit)
答案 3 :(得分:2)
也许尝试以下内容:
SELECT id,name,alarmId,alarmUnit,alarmLevel
FROM table
WHERE id IN (SELECT Max(id) FROM table GROUP BY alarmId, alarmUnit)
您可能必须在子查询选择中包含alarmId和alarmUnit。
答案 4 :(得分:2)
select id, name, alarmID, alarmUnit, alarmLevel
from (select max(id) as id
from table
group by alarmID, alarmUnit) maxID
inner join table
on table.id = maxID.id