How can you select max(table column), and on the from clause declare another table column? It doesn't make any sense - can anyone explain?
SELECT
Ord.SalesOrderID, Ord.OrderDate,
(SELECT MAX(OrdDet.UnitPrice)
FROM Sales.SalesOrderDetail AS OrdDet
WHERE Ord.SalesOrderID = OrdDet.SalesOrderID) AS MaxUnitPrice
FROM
Sales.SalesOrderHeader AS Ord;
A sql
SELECTquery always returns what’s called a “recordset”, no matter how simple or fancy the query is. For example, this will return a “recordset” with 2 columns and however many rows are in the tableBIRDSmatching the name “Bluebird” or “Cardinal”:Now, if you wanted to further narrow down what you’re querying the database for, sql lets you “query the query”, if that’s what you want to do:
^^^ This second query uses the recordset from the first query in place of a table.
This “inner query” is called a “subquery”.
You can also use subqueries in individual columns, like so:
^^^ This third query uses a subquery to fetch the average population of birds matching the color of each bird returned in the “outer” query. So, the final recordset returned will have two columns: “NAME” and “AVGPOP”.