Is there a way to do FIRST () in SQL Server?

From my old days of access, there was the First () function, which allowed you to get the first line as an aggregate function. Is there an equivalent in SQL Server?

SELECT c.ID , p.ID , FIRST(p.ProductName) , SUM(fee.Amount) from Fee as f INNER JOIN Product as p ON p.ID = f.ProductID INNER JOIN Customer as c ON c.ID = p.CustomerID GROUP BY c.ID, p.ID 

Edit: I just wanted to get the value from any string, since they will all be the same. I tried to be beautiful in the database and let him just give me the first one he finds :)

+4
source share
4 answers

Well, it depends.

Do you mean any string? Then you can use MIN or MAX, it should work with most data types.

However, if you mean "the first line you can find," then the answer will be no.

This is similar to telling the database engine that "I want you to give me a specific string that meets these criteria, and one of the criteria is that you can give me any string you want."

The reason for this is that if you do not order the lines, there is no concept of the first, and you cannot arrange the lines in any meaningful way that will work with the group in this way.

+5
source

You can try:

 SELECT c.ID, p.ID, (SELECT TOP 1 ProductName FROM Product ORDER BY ID) AS ProductName, SUM(fee.Amount) FROM Fee as f INNER JOIN Product as pON p.ID = f.ProductID INNER JOIN Customer as cON c.ID = p.CustomerIDGROUP BY c.ID, p.ID 

This first product gets directly from the Product table as a subquery. ORDER BY ID in the subquery should get you the first ProductName in the Product table.

+4
source

You can do SELECT TOP 1 * FROM ... to get only the first row.

+2
source

Don't know what I know, just use MIN ()

+1
source

All Articles