How do I implement First() and Last() aggregates like Access in MS-SQL?

Posted on 2006-05-02
Last Modified: 2008-03-06
Hi!  I need First() and Last() aggregates for MS-SQL that work like the same-named aggregates in Access.  My specific use is the I have financial "tick" values (date/time with price) that I want to roll up into a standard Open/High/Low/Close bar.  Min() and Max() work great for the Low and High values but I need something to get the first (Open) and last (Close) values as well.  I will be grouping the bars on one-minute intervals.  Any help in this regard would be greatly appreciated.  Thanks....
Question by:lsberman
    1 Comment
    LVL 142

    Accepted Solution

    sql server does not really have the First and Last, you can however implement a subquery getting the first and last values for a given group of data and related to a certain order

    select id, min(value) as min_value , max(value) as max_value
    , ( select top 1 value from yourtable i where = order by somefield asc   ) as first_value
    , ( select top 1 value from yourtable i where = order by somefield desc ) as last_value
    from yourtable t
    group by

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    In this article—a derivative of my blog post (—I will explore a few different perspectives on which week today's date falls within using Microsoft SQL Server. First, to frame this stu…
    This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
    This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
    This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now