I am new to SQL query. Can you please help me with the following?
id value quotePointId asOfTime
I craeted this query, it works, but I bet there is a better and more efficient way to do it, can anyone out there help?
select q.*
from (
select QuoteObservations.id, QuoteObservations.value, QuoteObservations.quotePointId, max(QuoteObservations.asOfTime) as asOfTime, QuoteObservations.dataProviderId, qp.quoteType
from [QuoteObservations]
inner join QuotePoints qp
on qp.id = QuoteObservations.quotePointId
where quotePointId = 1
group by QuoteObservations.id, QuoteObservations.value, QuoteObservations.quotePointId, QuoteObservations.dataProviderId
) q
inner join (
select QuoteObservations.id, QuoteObservations.value, QuoteObservations.quotePointId, max(QuoteObservations.asOfTime) as asOfTime, QuoteObservations.dataProviderId, qp.quoteType
from [QuoteObservations]
inner join QuotePoints qp
on qp.id = QuoteObservations.quotePointId
where quotePointId = 2
group by QuoteObservations.id, QuoteObservations.value, QuoteObservations.quotePointId, QuoteObservations.dataProviderId
) p
on q.id = p.id
inner join (
select QuoteObservations.id, QuoteObservations.value, QuoteObservations.quotePointId, max(QuoteObservations.asOfTime) as asOfTime, QuoteObservations.dataProviderId, qp.quoteType
from [QuoteObservations]
inner join QuotePoints qp
on qp.id = QuoteObservations.quotePointId
where quotePointId = 10
group by QuoteObservations.id, QuoteObservations.value, QuoteObservations.quotePointId, QuoteObservations.dataProviderId
) s
on s.id = p.id
SELECT
QuoteObservations.id,
QuoteObservations.value,
QuoteObservations.asOfTime,
QuotePoints.quoteType
FROM
QuoteObservations
LEFT JOIN QuotePoints
ON QuoteObservations.quotePointId = QuotePoints.id
WHERE
QuotePoints.quoteType = 1
OR QuotePoints.quoteType = 2
ORDER BY
QuoteObservations.asOfTime DESC
LIMIT 1;
You need to remove the WHERE condition that is limiting the results on QuoteObservations.id =1 OR QuoteObservations.id = 2
Here is the revised SQL, with that condition removed. I have also moved the JOIN conditon into the JOIN clause.
SELECT QuoteObservations.id,
QuoteObservations.value,
QuoteObservations.quotePointId,
max(QuoteObservations.asOfTime) as asOfTime,
QuoteObservations.dataProviderId,
QuotePoints.quoteType
FROM QuoteObservations
INNER JOIN
QuotePoints
ON QuoteObservations.quotePointId = QuotePoints.id
WHERE QuotePoints.quoteType in (1,2)
group by
QuoteObservations.id,
QuoteObservations.value,
QuoteObservations.quotePointId,
QuoteObservations.dataProviderId,
QuotePoints.quoteType;