SQL QUERY subtraction query

Posted on 2012-08-30
Last Modified: 2012-08-30
I need to preform subtraction on a table and display the difference.
I need to subtract 2 times

id        Date
1         2012-04-20 10:48:15.363
2         2012-04-20 10:48:15.383
3         2012-04-20 10:48:37.643
4         2012-04-20 10:48:37.793

I need to subtract id 2 Date - id 1 Date
which is .20
Question by:Leo Torres
    LVL 15

    Expert Comment

    If you are just doing two specific IDs you could do something like this.

       CAST((SELECT date FROM YourTable WHERE ID = 1) - (SELECT Date FROM YourTable WHERE ID = 2) AS Time)
    LVL 25

    Accepted Solution

    You could also do
    SELECT, DATEDIFF(ms, b.Date, a.Date)
    FROM yourtable a
    INNER JOIN yourtable b ON + 1 =

    if only two rows

    SELECT, DATEDIFF(ms, b.Date, a.Date)
    FROM yourtable a
    INNER JOIN yourtable b ON + 1 =
    WHERE = 1
    LVL 8

    Author Closing Comment

    by:Leo Torres
    Thank you!

    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

    Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
    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.
    Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
    Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties

    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