Avatar of Sonia Bowditch
Sonia Bowditch
Flag for Guernsey asked on

T-SQL Select First Date, Last Date with Amounts

Hello Experts,

I am trying to write a SQL statement which will give me the First and Last dates with the amounts.

I am using the following SQL to get the total first date for the ref and the dates for first and last entry but I need to get the first entry for that ref and the last entry with the first amount and last amount.  I have tried using FIRST and LAST functions but I am not getting the results I want.

SELECT COUNT(DISTINCT ref) AS REF,
              MIN (FIRST_DATE) AS FIRST_DATE,
              MAX(LAST_DATE) AS LAST_DATE,
             SUM(FIRST_AMOUNT) AS FIRST_AMOUNT,
             SUM(LAST_AMOUNT) AS LAST_AMOUNT,
FROM TABLE
GROUP BY REF
Select-First-and-Last-Amount.xlsx
* T-SQLMicrosoft SQL Server

Avatar of undefined
Last Comment
Vitor Montalvão

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Ryan Chong

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
ste5an

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Sonia Bowditch

ASKER
Hello Ste5an,

The reason for the last date being before the first date is because I created a random set of data.  I have amended the data to  ensure the ref column is unique.  I need to select the first and last date and amount for the Customer column.

Hopefully, this clears up some of the confusion.

Thanks
Select-First-and-Last-Amount.xlsx
Sharath S

Is the data in the attached sheet raw data or expected result? Provide some sample data from your table and expected result.
Sonia Bowditch

ASKER
Hello Sharath,

I have added a mock up of what I am hoping to get out of the data.  

Thanks.
Select-First-and-Last-Amount.xlsx
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Vitor Montalvão

Sonia, is this issue solved?