如何获得第一个和最后一个记录?一步解决方案?

时间:2015-03-24 14:35:03

标签: mysql sql where

我有以下数据表。

 Record  Date        Price 
 A       3/1/2015    5 
 A       3/2/2015    6 
 A       3/3/2015    7 
 A       3/4/2015    10 
 B       2/1/2015    4 
 B       2/2/2015    6 
 B       2/3/2015    15 
 B       2/4/2015    2 

如何输出一个表格,该表格仅显示表格中第一个日期的每条记录的第一个价格和最后一个价格以及表格中的最后一个日期。输出列将是记录,第一价格,最后价格。我正在寻找一个易于实现的一步解决方案,以创建自定义视图。

所需的输出是:

 Record     FirstPrice   LastPrice
 A          5            10 
 B          4            2 

3 个答案:

答案 0 :(得分:4)

也许你正在寻找这样的东西?

select R.Record, FD.Price as MinPrice, LD.Price as MaxPrice
from Records R
join (
    select Price, R1.Record
    from Records R1
    where Date = (select MIN(DATE) from Records R2 where R2.Record = R1.Record)
  ) FD on FD.Record = R.Record
join (
   select Price, R1.Record
    from Records R1
    where Date = (select MAX(DATE) from Records R2 where R2.Record =     R1.Record)
  ) LD on LD.Record = R.Record
group by R.Record

http://sqlfiddle.com/#!9/d047b/26

答案 1 :(得分:0)

获取按记录字段分组的最小和最大聚合日期,并加入返回根数据。如果您可以在同一日期为同一记录字段创建多个记录,则必须使用min,max或avg才能获得该日期的一个值。

SQLFiddle:http://sqlfiddle.com/#!9/1158b/3

SELECT anchorData.Record
,      firstRecord.Price
,      lastRecord.Price
FROM (
    SELECT Record
    ,      MIN(Date) AS FirstDate
    ,      MAX(Date) AS LastDate
    FROM   Table1
    GROUP BY Record
    ) AS anchorData
JOIN   Table1 AS firstRecord
ON     firstRecord.Record = anchorData.Record
AND    firstRecord.Date = anchorData.FirstDate
JOIN   Table1 AS lastRecord
ON     lastRecord.Record = anchorData.Record
AND    lastRecord.Date = anchorData.LastDate

答案 2 :(得分:-1)

“为了创建一个自定义视图。”...你想在Oracle / MySql中作为CREATE VIEW或只是一个查询/选择语句吗?