Solved

Max Date and Group By SQL Server

Posted on 2014-10-16
2
83 Views
Last Modified: 2014-10-17
I'm working on a CRM report.  I want to show the last contact history per account.  The history is all housed in one table, account information in the other.

Pertinint fields in History are:

HistoryID, Account, Date
Where there can be many dates and history IDs related to the account

I'm trying to find the latest date by doing a MAX expression on the date field and grouping by the Account field -- that works fine, but I need to return the HistoryID related to that record in order to join it to the account table.

I hope this makes enough sense for you to help.

For now, I've used a query joining the account to history with all history and then filtered within SSRS to get the results for this one report, but I'd like to create a view of just the HistoryID, Account, Date from the History table for future use.
0
Comment
Question by:akscott
2 Comments
 
LVL 24

Accepted Solution

by:
chaau earned 500 total points
ID: 40385950
These type of queries are best performed with a help of a window function:
with a as (
Select Account, HistoryID, Date, ROW_NUMBER() OVER (PARTITION BY Account ORDER BY Date DESC) as rn
From History )
SELECT Account, HistoryID, Date FROM a WHERE rn = 1

Open in new window

0
 

Author Comment

by:akscott
ID: 40386737
I don't understand it, but it worked. There's a section on partitions in my SQL book -- looks like I need to read that.  Thank you!
0

Featured Post

Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
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.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

831 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