sql,c,选择具有最高时间戳和两个cols的两行

时间:2013-08-06 18:42:00

标签: sql select

我问了同样的问题,但没有得到最终答案,所以,再试一次。 有两种类型的报价,回购利率或最后价格,我想选择具有最高日期时间的回购利率,以及两个表格中具有最高日期时间的最终价格。 这是我从最初的帖子得到帮助的答案,但如果两者都存在,我需要两个记录(回购和最后价格)。任何人都可以通过以下更改请求帮助:非常感谢!!

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;

1 个答案:

答案 0 :(得分:0)

您要求返回两行。以下SQL将完成您所描述的内容:

SELECT TOP(1) QuoteObservations.id, 
    QuoteObservations.value, 
    QuoteObservations.quotePointId,
    QuoteObservations.asOfTime, 
    QuoteObservations.dataProviderId,
    QuotePoints.quoteType 
FROM    QuoteObservations
INNER JOIN QuotePoints 
ON      QuoteObservations.quotePointId = QuotePoints.id 
WHERE   QuotePoints.quoteType = 1 -- Get most recent row for quoteType 1
ORDER BY QuoteObservations.asOfTime DESC

UNION ALL 

SELECT TOP(1) QuoteObservations.id, 
    QuoteObservations.value, 
    QuoteObservations.quotePointId,
    QuoteObservations.asOfTime, 
    QuoteObservations.dataProviderId,
    QuotePoints.quoteType 
FROM    QuoteObservations
INNER JOIN QuotePoints 
ON      QuoteObservations.quotePointId = QuotePoints.id 
WHERE   QuotePoints.quoteType = 2 -- Get most recent row for quoteType 2
ORDER BY QuoteObservations.asOfTime DESC