Query to find the difference between the last date and the second to the last date

Hi all,
Hope all is well.
I am working on the following problem because I am trying to improve my MS SQL skills. But I am stuck at the moment and I wonder if you could provide some assistance please. Here is the issue:
Table 1: Dividends
divId
ExDate
RecordDate
PayDate
Amount
Yield
symId
1
2013-02-19
2013-02-21
2013-03-14
0.23
0.00000
3930
2
2012-11-13
2012-11-15
2012-12-13
0.23
0.00849
3930
3
2012-08-14
2012-08-16
2012-09-13
0.20
0.00664
3930
4
2012-05-15
2012-05-17
2012-06-14
0.20
0.00662
3930
5
2012-02-14
2012-02-16
2012-03-08
0.20
0.00661
3930
6
2011-11-15
2011-11-17
2011-12-08
0.20
0.00748
3930
7
2011-08-16
2011-08-18
2011-09-08
0.16
0.00631
3930
8
2011-05-17
2011-05-19
2011-06-09
0.16
0.00653
3930
9
2011-02-15
2011-02-17
2011-03-10
0.16
0.00594
3930
10
2010-11-16
2010-11-18
2010-12-09
0.16
0.00620
3930
11
2010-08-17
2010-08-19
2010-09-09
0.13
0.00526
3930
12
2010-05-18
2010-05-20
2010-06-10
0.13
0.00455
3930
13
2010-02-16
2010-02-18
2010-03-11
0.13
0.00459
3930
Table 2: Tickers
symId
Symbol
Name
Sector
Industry
1
A
Agilent Technologies Inc.
Technology
Scientific & Technical Instruments
2
AA
Alcoa, Inc.
Basic Materials
Aluminum
3
AACC
Asset Acceptance Capital Corp.
Financial
Credit Services
4
AADR
WCM/BNY Mellon Focused Growth ADR ETF
Financial
Exchange Traded Fund
5
AAIT
iShares MSCI AC Asia Information Tech
Financial
Exchange Traded Fund
6
AAME
Atlantic American Corp.
Financial
Life Insurance
7
AAN
Aaron's, Inc.
Services
Rental & Leasing Services
8
AAON
AAON Inc.
Industrial Goods
General Building Materials
9
AAP
Advance Auto Parts Inc.
Services
Auto Parts Stores
10
AAPL
Apple Inc.
Technology
Personal Computers
11
AAT
American Assets Trust, Inc.
Financial
REIT - Office
12
AAU
Almaden Minerals Ltd.
Basic Materials
Industrial Metals & Minerals
I am trying to check the last date (i.e. max date) and also check the penultimate date (i.e. the second to the last date).  And then find the difference between the two (i.e. last date minus penultimate
date).
I would like to do that for each of the companies listed in Table 2: Tickers.  I am able to do it for just one company (MSFT) using the queries below:
SELECT
[First] = MIN(ExDate),
[Last] = MAX(ExDate),
[Diff] = DATEDIFF(DAY, MIN(ExDate), MAX(ExDate))
FROM (
SELECT TOP 2 Dividends.ExDate
FROM Dividends, Tickers
WHERE Dividends.symId=Tickers.symId
AND Tickers.Symbol='MSFT'
ORDER BY ExDate DESC
) AS X
Outputs the following result:
First
Last
Diff
2012-11-13
2013-02-19
98
But what I would like instead is to be able to output something like this:
Symbol
First
Last
Diff
MSFT
2012-11-13
2013-02-19
98
AAN
2012-11-13
2012-12-14
1
X
2012-11-13
2012-12-14
1
Can anyone please let me know what do I need to add on my query in order to achieve the desired output?
Any help would be greatly appreciated.
Thanks in advance. 

Could you try this?
create table Ticker (SymbolId int identity primary key, Symbol varchar(4))
insert into Ticker (Symbol) values ('MSFT'), ('ORCL'), ('GOOG')
create table Dividend (DividendId int identity, SymbolId int constraint FK_Dividend foreign key references Ticker(SymbolId), ExDate datetime, Amount decimal(18,4))
insert into Dividend (SymbolId, ExDate, Amount) values
(1, '2012-10-1', 10),
(1, '2012-10-3', 1),
(1, '2012-10-7', 7),
(1, '2012-10-12', 2),
(1, '2012-10-23', 8),
(1, '2012-10-30', 5),
(2, '2012-10-1', 10),
(2, '2012-10-6', 1),
(2, '2012-10-29', 7),
(3, '2012-10-1', 22),
(3, '2012-10-3', 21),
(3, '2012-10-7', 3),
(3, '2012-10-12', 9)
WITH cte
AS (SELECT t.Symbol,
d.ExDate,
d.Amount,
ROW_NUMBER()
OVER (
partition BY Symbol
ORDER BY ExDate DESC) AS rownum
FROM Ticker AS t
INNER JOIN Dividend AS d
ON t.SymbolId = d.SymbolId),
ctedate
AS (SELECT Symbol,
[1] AS maxdate,
[2] AS penultimatedate
FROM cte
PIVOT( MIN(ExDate)
FOR RowNum IN ([1],
[2]) ) AS pvtquery),
cteamount
AS (SELECT Symbol,
[1] AS maxdateamount,
[2] AS penultimatedateamount
FROM cte
PIVOT( MIN(Amount)
FOR RowNum IN ([1],
[2]) ) AS pvtquery)
SELECT d.Symbol,
MIN(MaxDate) AS maxdate,
MIN(penultimatedate) AS penultimatedate,
DATEDIFF(d, MIN(penultimatedate), MIN(MaxDate)) AS numberofdays,
MIN(MaxDateAmount) AS maxdateamount,
MIN(penultimatedateAmount) AS penultimatedateamount,
MIN(MaxDateAmount) - MIN(penultimatedateAmount) AS delta
FROM ctedate AS d
INNER JOIN cteamount AS a
ON d.Symbol = a.symbol
GROUP BY d.Symbol
ORDER BY d.Symbol
Please mark this reply as the answer or vote as helpful, as appropriate, to make it useful for other readers.
Thanks!
Aalam | Blog (http://aalamrangi.wordpress.com)

Similar Messages

  • What is the difference between MacBook pro 2011 and 2012

    What is the difference between MacBook pro 2011 and 2012

    understanding that at the time of the question, there has not been any Macbook Pro 2012, now it is later and there is.
    The difference is:
    -CPU being used (2011 models: Sandy Bridge, 2012 models: Ivy Bridge)
    -Graphics (2011: intel 3000 + on 15"/17" ATI, 2012: intel 4000 + on 5"/17" nvidia Geforce 650M)
    -USB (2011: USB2.0 only, 2012: USB3.0)
    -Bluetooth (2011. 2.1 + EDR, 2012: 4.0)
    Ivy Bridge CPUs are smaller and are a little bit more energy-efficient.
    Other than that, currently the devices are not much different in respect to performance (Apple's graphics driver performance is known to increase during upgrades, though, so the performance gap may widen up)

  • What is the difference between saving to "Documents" and "Macintosh HD" and when should you use each one?*

    What is the difference between saving to "Documents" and "Macintosh HD" and when should you use each one?

    When you save to the folder with the little house icon, the file is placed at
    /Users/your_user_name/
    You would really have to go out of my way to save at:
    (the shortcut for the Boot Drive, regardless of its name).
    I am not sure how you decided that Time Machine is not saving your files. The default is for Time Machine to do incremental Backups of everything on all attached drives, except for certain temporary information in Cache files. If you have four Users, Time Machine will back them all up.
    Looking at the raw Time Machine backups will tell you very little, because it does lots of its work with Hard Links, and because it does incremental backups, so only files that changed since the last Backup are saved at thet cycle. The way to determine whether Time Machine is saving things is to display the window you care about in the Finder, then invoke the "Star wars"/ "Back, back, back in time" Interface.

  • The difference between AIR-ANT5135D-R and AIR-ANT5135DB-R

    Hi,
    Anyone know what is the difference between AIR-ANT5135D-R and  AIR-ANT5135DB-R ?
    From the dynamic configuration tools for 1252 and 1242, AIR-ANT2422DB-R is inside one of the antenna option.
    However, I can't find it in the "Cisco Aironet Antennas and Accessories Reference  Guide"
    http://www.cisco.com/en/US/prod/collateral/wireless/ps7183/ps469/product_data_sheet09186a008008883b.html
    Inside the document there is only AIR-ANT5135D-R.
    likewise for the 2.4 GHz,  AIR-ANT2422DB-R is inside the dynamic configuration tools and not inside "Cisco Aironet Antennas and Accessories Reference  Guide"
    Any help would be appreciated
    Thanks,
    Richard

    Found the difference, AIR-ANT5135DB-R and       AIR-ANT2422DB-R are  non-articulating antennas.
    Thanks!
    Richard

  • What is the difference between PO Charge Account and PO Accrue Account ?

    Hi
    On Requistion's Distribution screen , there is a A/c codes exists : PO Charge , Accrue, Budget & Variance .
    Can anyone explain me the exact purpose of the same and what is the difference between PO Charge Account and PO Accrue Account ?
    regards
    Thanks
    SD

    Hi Sanjay,
    Here is the OA help (11i) :
    Entering Purchase Order Distributions:
    6. Enter the purchasing accounts. When you save your changes in this window, Purchasing uses the Account Generator to automatically create the following accounts for each distribution:
    Charge: the account to charge for the cost of this item in the purchasing operating unit
    Accrual: the AP accrual account in the purchasing operating unit
    Variance: the invoice price variance account in the purchasing operating unit
    Destination Charge: the account to charge for the cost of this item in the destination operating unit
    Destination Variance: the invoice price variance account in the destination operating unit
    Note: The last two accounts are created only if the receiving destination operating unit is different than the purchasing operating unit and there is a transaction flow defined between the two organizations.
    If you are using encumbrance control, Purchasing also creates the following account for each distribution:
    Budget: the encumbrance budget account
    The Account Generator creates these accounts based on predefined rules. See: Using the Account Generator in Oracle Purchasing.Hope it helps
    Xavier

  • What is the difference between quicktime 7 pro and quicktime x

    What is the difference between quicktime 7 pro and quicktime x

    QuickTime Pro 7 is a very useful video tool.  You can make simple edits to video files, cut-n-paste multiple video files together into one, save the video or transcode it into a variety of common video formats, use it to analyze a video to see which codec it's in, and even play videos in professional settings.
    QuickTime X is completely useless.
    With QT X and Final Cut X, Apple has completely abandoned the professional video market.  Both of these software packages are dumbed down for Windows users, and are intentionally designed to anger and alienate the professional user that has come to rely on Apple software for their video needs over the last 20 years.  Final Cut X is really just iMoviePro. If I wanted iMovie, I'd use iMovie, but I need a professional video app, not a kiddie video app.  Therefore I can not use FCPX.
    I have work to do, under strict deadlines and budget limits.  FCPX and QTX actively prevent me from getting any work done at all.  Apple has left me no choice.  I have to go back to Adobe Premiere or Avid Media Composer since these are still professional applications.  Final Cut and QuickTime have been turned into kiddie-style iMovie-like apps that have no functionality whatsoever.
    Apple is heading in a very disappointing direction.  They have a history of cutting off legacy items without notice.  They have decided that optical media is over and everything is online.  But my clients don't have that luxury.  I still have to deliver products on DVD and increasingly Blu-Ray.  Apple's obstinate refusal to support Blu-Ray has cost me clients, and I've had to resort to third-party software and hardware.
    Apple has abandoned the professional video market.

  • From ABAP view, what is the difference between version 4.7 and ECC 6.0 ?

    Hi,
    I am a ABAP developer. I want to know the difference between version 4.7 and ECC 6.0 from a programmer
    perspective.
    I also want to know  what is obsoleted and what is enhanced.
    Thanks.
    Best Regards,
    Chris Gu

    I'm not sure if any of this is in your 4.7 version, but I know it wasn't available in our 4.6C before we upgraded and we have found the following extremely helpful in ECC 6.0:
    1.  The new ABAP Debugger - Search SDN and you'll probably find a bunch of info on these enhancements
    2.  The Enhancement Framework - this is a great new framework allowing enhancements to standard SAP programs without having to use "core Mods".  Had we known about it prior to our upgrade, we could have probably eliminated 75% or so of our custom Z Programs which are copies of standard SAP code  and 100% of our core mods (of which we only have a handful)
    3. Code Inspector and more importantly the ability to turn it on to automatically run when releasing a transport.
    4. The ABAP workbench has changed a bit with a new editor including some minimal code completion.
    5.  Automatic generation of services from any remote enabled function module.
    These are just a few of the things that I've found helpful in an upgraded environment.

  • What's the difference between wcc system components and standard components

    hi Experts,
    My customer has a question on the difference between wcc system components and standard components, I didn't find it from doc, anyone can help on answering this?
    Best regards

    Hi ,
    System components are those which are providing the basic functionalities on UCM server by default . Standard components are those which are provided as-in on the server but need to be enabled per case basis . For example Framework Folders which is not necessary for the basic functionalities but is needed if user wants to .
    This guide gives the administration level overview for UCM  : http://docs.oracle.com/cd/E23943_01/doc.1111/e10792/toc.htm
    Hope this helps .
    Thanks,
    Srinath

  • The difference between VGA, DVI-D and ADC?

    Hi.
    The difference between VGA, DVI-D and ADC and which should be used with a T244 widescreen monitor into a Quicksilver G4 with a GeForce2 MX nVIDIA (0x10de) card. What's a good upgrade card if the above is not good enough?
    Thank you for your input.
    Walter

    Look at this link http://en.wikipedia.org/wiki/DigitalVisualInterface
     Cheers, Tom

  • The difference between Telepresence Content Server and MSE 3500

    Good day! Could someone explain me what's the difference between Telepresence Content Server and MSE 3500? Why do I need to obtain two these devices for sorting out my tasks? I want to understand gist of the first and the second devices.

    In addition to what Jonathan posted above, here is a Capture Transform Share Solution Guide that goes over a little bit of what the TCS and MXE are and some possible deployment scenarios.
    In short, TCS is used to record video conferences or lectures that can be streamed on demand or live using various streaming or distribution methods.  One such distribution method is using the MXE 3500 to ingest the recordings from TCS and convert them to different media types and add in-video content such as logos etc.  However, from the MXE, you can't send the video back to the TCS for viewing, you'd need to send that off to another viewing portal such as Show and Share.

  • What is the difference between string != null and null !=string ?

    Hi,
    what is the difference between string != null and null != string ?
    which is the best option ?
    Thanks
    user8729783

    Like you've presented it, nothing.  There is no difference and neither is the "better option".

  • What is the difference between Wine, Wineskin, Winery and Wine Bottler, and how do I get Wine to *ACTUALLY* work in Mountain Lion?

    Ok, so this is my first post here and I am admittedly terrible at forums. Someone might say, "This was addressed in the ___________ thread by __________! Go read it!" --- that may be so but I've spent enough hours trying to google this problem into submission to no avail based on what is apparently working for others, so I would like a chance to get specific answers to specific questions that aren't from Mar 2011, etc.
    So first of all, I'm confused by all the various Wine programs/apps/whatevers. I've seen Wine, Wineskin, Winery, Wine Bottler, and at this point I wouldn't be surprised if there are even more than that. What's the difference between all of these and how do they work with one another? What do I actually need to get windows programs working?
    All of my google searches have led me to people giving out fish, but no one giving out fishing lessons. I'm not a pro at mac and windows and all that, but I'm a fairly bright individual who gets VERY frustrated, very quickly, when I don't understand the why and how of something I'm attempting.
    I've also found "answers" where the person attempting to help starts off helpful enough, but degrades into the most archaic of techno-babble after about 5-6 sentences. On the other hand, I've watched tutorials on youtube where the poster decides to skip (apparently crucial) sections of the tutorial, and mutters such gems as: "... you might wanna have to run Wine first before you can do anything, cuz I think it has to configure it and set up a bunch of stuff" 
    O.o
    A happy medium between techno-babble and the most basic of explanations would be ideal for me, and I'd imagine for others as well.
    Here is a summarized history of my relationship with Wine:
    Diablo II - I downloaded this awesome thing which ended up being... uh... I guess Diablo II in a Wineskin "wrapper". I'm not sure, all I know is that it's a D2 icon, and if I go to 'show package contents', it's got C drive, Program Files, et cetera inside of it. I double click it, it launches D2, and it works like a dream. <3
    'Vanilla Install' - That's what I heard someone call it. It was the command/terminal style install using xquartz and xcode found at http://www.davidbaumgold.com/tutorials/wine-mac/. I followed every instruction to the letter, and got all the way to '$ sudo port install wine', at which point it started going smoothly, free from the possible error he described regarding the installation of xcode, and then just failed after I left the room to use the restroom and came back. Please don't ask me to repeat what the error was, because honestly, after reading more things on the interwebs, I'm confused as to why it's even necessary to go through all of that, so I'd rather not try that route again anyways, rendering the error message quite possibly irrelevant.
    Wine + Wine Bottler - So I decided to try to seek out an easier method, as I know that one must exist that doesn't involve command lines. I found a video tutorial at http://www.youtube.com/watch?v=m0BBkISOcEA, and oh man would it be great if that method had actually worked. Again, I followed all instructions provided to procure my free fish, and at the point in the video where he declares that "xquarts or x11 will open" - it doesn't open. Nothing opens. I was trying to install Star Sonata, btw.
    So here I am, thoroughly worn out, frustrated at all the random places Wine is installed on my mac now, and just want someone to explain it all, from top down, without getting toooooooo technical on me. I know that might be asking a lot...

    ## I know that the poster has already found a solution, but the following is a possible answer for others that have similar issues.
    For Winebottler, just go to their website and download it. Run the program. Choose .wine as your prefix (best choice) or whatever suits you best. You'll need a functional X11. If you can't use the one that comes with your mac, download the latest one from the website.
    If your issue is one with Winebottler's Wine not running correctly due to X11, then you have a pretty ugly problem, although a simple upgrade is the best solution (Upgrade XQuartz.app).
    http://www.davidbaumgold.com/tutorials/wine-mac/#part-1
    The above website is the easiest way to get REAL wine on your computer. First of all, Wineskin WInery, etc. are NOT WINE. They are 3rd party apps that may use Wine or may have originally part of Wine, but they are no longer up to date with Wine. WineBottler is currently up to date with the stable releases of Wine (but not the maintenence releases).
    For the website tutorial and to run Wine on your mac without using a thrid party app, you will need to know a few things.
    First, you will need to know basic control of the command line. That means, sudo (you must know the administrator password to your computer), and the forms of cd (change directory).
    Second, you will need Xcode. Download 4.2 (stable) or whatever other versions you want, but beware: It is over 1 GB, and you will need time for it to work.
    Third, you will need to get MacPorts and configure it. The tutorial should have this data.
    When you download wine (use sudo port install wine-devel for the latest development release of wine), it will first download a lot of dependencies. This will take a while. After that, it will download wine itself.
    After obtaining wine, to run a program, open the terminal.app window.
    cd desktop/XYZ/ZYZ\ WRQ
    The above will first enter the desktop, then folder XYZ, then folder ZYZ WRQ. From here,
    wine th11e.exe
    Or whatever executable you are trying to open. (Using Subterranean Animism as my example).
    It should, in theory, run the program. Watch the terminal for errors. If there is an X11 problem, then it's not wine acting up. If the app crashes or has other issues, check the Wine Application Database to see if your app is compatible with wine.
    If you have any further questions or other things, feel free to reply; I may or may not get back to you, but there's a good chance that someone will come in eventually. Otherwise, the Wine Wiki should have some information.

  • What is the difference between a mac-book, and an I-pad?

    What is the difference  between a mac-book and an I-pad?

    The Macbook is a computer (running Mac OS X), an iPad is a tablet (running iOS). What are thinking of using it for ? The Mac is more powerful than iPad, so if you need processing power then that will be better suited for your needs. If you will mainly be using it for media (films, music), internet browsing, emails, ebooks, then an iPad would be sufficient.
    Macbook Air : http://www.apple.com/macbook-air/
    MacBook Pro : http://www.apple.com/macbook-pro/
    iPad Air : http://www.apple.com/ipad-air/

  • In ical, how can you tell the difference between a meeting invite and email?

    When you send a meeting invite in ical, does the recipient receive a different icon in their inbox to differentiate from an email?

    For service stock you can't tell the difference between a new iPad and a refurbished one. Both will come in a plain brown box with the same pattern in model numbers. If you mean between a refurbished one and one new at retail, then other than the obvious difference in packaging, I've read that the model number on refurbished units starts with the letter "F", though I've not confirmed that.
    Regards.

  • What is the difference between NetWeaver 7.3 and NetWeaver 7.03?

    Hi Experts,
    Can anydoby explain me the difference between NetWeaver 7.3 and NetWeaver 7.03? or say difference between NetWeaver 7.2 and NetWeaver 7.02?
    I have been confused by these 2 terms. As far as I know, the features of AS ABAP in NetWeaver 7.3 and NetWeaver 7.03 are almost same. The same applies to NetWeaver 7.2 and NetWeaver 7.02.
    BTW, as I know the BS2011 are based on NetWeaver 7.03, PI 7.3 are based on NetWeaver 7.3.
    Thanks and Best Regards
    Fei
    Moderator message: not directly related to ABAP development, please search for available information, e.g. in the Netweaver forums.
    Edited by: Thomas Zloch on Mar 1, 2012

    Vivianemt wrote:
    I have an Olympus OM D E 5, I think only Lightroom 4.3 is useable.
    The Olympus OM-D E-M5 was first supported in Lightroom 4.1
    http://helpx.adobe.com/creative-suite/kb/camera-raw-plug-supported-cameras.html
    Vivianemt wrote:
    Can I upgrade from  LR 4 to 4.3??
    Yes, all 4.x dot releases (updates) are free of charge to all version 4 owners.
    You only pay again for the next major version upgrade = version 5  unless you're a Cloud member where all upgrades and updates are included in the membership fee.

  • What is the difference between Safari 6.0 and 6.0.2?

    What is the difference between Safari 6.0 and 6.0.2?

    here is a copy of the text from Software Update
    Safari 6.0.2 is recommended for all users running OS X Lion v10.7.5
    and includes security updates.
    For more information, please visit: http://support.apple.com/kb/HT1222

Maybe you are looking for

  • Problem with Current row of a VO???

    I have a Advanced table region in which i add many rows..and i get the data in to it from the lov page (lov mappings). for each row i add... i have to set a item in main page table region doing some validations the data i get from lov region. with ex

  • Cannot open pdf files or uninstall adobe reader

    I downloaded Reader X but could not open any pdf files so tried to reinstal.  I got the message that it was already installed so tried to uninstall but could not do it. The message was to say that it was using certain files and to close explorer.  Do

  • ITunes 11 - a complete catastrophe!

    It's been 6 month since the release of iTunes 11 and I haven't managed yet to work with it. I hate it! What's wrong with iTunes 11? The sorting by Title, Album Interpret, Play Lists or Radio is confusing. Every page has its own Layout and I once I sw

  • Access on a OAS JMS through OSB

    Hi, Does anybody know how can I configure OSB(Business Service) to access a JMS Queue on a Oracle Application Server? I understand that i have to configure JMS module or something on webLogic console. But I really don't know what. Thanks in advance.

  • Album titles gone

    Hello, I recently signed into iTunes (after a while away from the computer) and found that all of my iTunes album information has been deleted. Over the years I have painstakingly gone through and added the album name for all of my songs (around 1000