Editing
MSSQL Cookbook
(section)
Jump to navigation
Jump to search
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Selecting the earliest records grouped by some other criteria== '''Goal:''' You want to get the records with the earliest date for each group. '''Solution:''' Use <code>PARTITION BY</code> (SQL Server 2005 or greater). <syntaxhighlight lang="sql"> WITH groupedCTE AS ( SELECT id , groupName , createDate /* defining the group and creating a way to target by date value */ , ROW_NUMBER() OVER (PARTITION BY groupName ORDER BY createDate) AS row FROM myTable ) SELECT id , groupName , createDate FROM groupedCTE /* filter down to the earliest record */ WHERE row = 1 /* ORDER BY clause here isn't contributing to the solution; just demonstrates sorting the results */ ORDER BY groupName </syntaxhighlight> '''Solution:''' Another approach using <code>PARTITION BY</code> The first solution seems more clear, and maybe it's also more efficient? <syntaxhighlight lang="sql"> SELECT id , groupName , createDate FROM ( SELECT id , groupName , createDate MAX(createDate) OVER (PARTITION BY groupName) MaxCreateDate FROM myTable ) a1 /* filter down to the earliest record */ WHERE groupName = groupName AND dtView = MaxCreateDate /* ORDER BY clause here isn't contributing to the solution; just demonstrates sorting the results */ ORDER BY groupName </syntaxhighlight> '''Note''' that while <code>PARTITION BY</code> makes for very clear code, it is not super-fast for execution. [[Category:Web Development]] [[Category:MSSQL]]
Summary:
Please note that all contributions to Littledamien Wiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Littledamien Wiki:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Navigation menu
Personal tools
Not logged in
Talk
Contributions
Create account
Log in
Namespaces
Page
Discussion
English
Views
Read
Edit
View history
More
Search
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Tools
What links here
Related changes
Special pages
Page information