문제

I am using SQL Server Compact 4.0 and am trying to get one query to return a single record with a column Alarm based on the maximum identity when another column Cleared is NULL.

This works:

SELECT Id, Alarm 
FROM Alarm_History 
WHERE Cleared IS NULL

Giving me half the answer. The problem is that it returns several records.

This also works:

SELECT MAX(Id) 
FROM Alarm_History 
WHERE Cleared IS NULL

And it gives me the other half of the answer, but I can't get the value "Alarm" that I am looking for.

But they DON'T work together as in:

SELECT Id, Alarm 
FROM Alarm_History 
WHERE Cleared IS NULL AND Id = MAX(Id)

OR

SELECT MAX(Id), Alarm 
FROM Alarm_History 
WHERE Cleared IS NULL

With the queries above I can do two consecutive queries to get the result back, but I don't think this is very efficient. Is there a way to do this in one trip to the database?

Thanks Jeff

도움이 되었습니까?

해결책

You could do it with max and a join, but that would be far too complicated. Instead, you can just try:

SELECT TOP 1 Id, Alarm
FROM Alarm_History
WHERE Cleared IS NULL
ORDER BY Id DESC

Note: what happens if two alarms have max id ? Well, that shouldn't happen (Id is unique). But that's an interesting problem nevertheless (suppose the field is not Id but Price, and you want all alarms with max price, and you don't know how many there'll be, so you cannot use TOP 1 anymore). You'll have to use a CROSS JOIN;

SELECT Id, Price
FROM Alarms
JOIN (SELECT MAX(Price) as maxPrice FROM Alarms) b
WHERE Alarms.Price = b.maxPrice

다른 팁

Don't think "max". Think "order by". Try this:

SELECT TOP 1 Id, Alarm
FROM Alarm_History
WHERE Cleared IS NULL
ORDER BY Id DESC;

That way, you can get all the fields you want associated with the max id.

Try,

SELECT Id, Alarm FROM Alarm_History WHERE ID in (SELECT MAX(Id) FROM Alarm_History WHERE Cleared IS NULL)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top