SQL question

Status
Not open for further replies.

Jehos

Ars Legatus Legionis
55,560
I'm not sure exactly what this is called, so I'm having a hard time Googling for it.

Let's say I want to pull the details of the first order made by each customer. I know I can do something like this:

Code:
SELECT o.Customer, o.OrderDate, o.MoreStuff1, o.MoreStuff2
FROM Orders o
INNER JOIN (
	SELECT Customer, MIN(OrderDate) AS OrderDate
	FROM Orders
	GROUP BY Customer
) a
	ON o.Customer = a.Customer AND o.OrderDate = a.OrderDate

It seems a little inelegant though, and also a super common problem. Is there a built-in SQL statement or function that does this, i.e. do some grouping operation to a result set and then let you get at all the other columns in that row without grouping by those columns? So the earliest order per customer, max total spent per customer, etc?
 

wallinbl

Ars Legatus Legionis
14,319
Subscriptor
[url=http:/civis/viewtopic.php?p=30060937#p30060937:2avrvios said:
Jehos[/url]":2avrvios]Thanks, looking up window functions was helpful. Looks like FIRST_VALUE is really what I want to use.

I figured it had to be a solved problem at this point.
There's a lot available now that wasn't around until more recently. The various window functions are worth learning, as they're very fast and often result in much more concise queries. They're worth learning and mastering, and possibly refactoring some of the ugly hacks that were in place before they were around.
 
Status
Not open for further replies.