all groups > sql server (alternate) > november 2005 >
You're in the

sql server (alternate)

group:

Query question



Query question Yannick Turgeon
11/29/2005 11:38:01 AM
sql server (alternate): Hello all,

Say we've got these data:

----------------------------------------
CREATE TABLE #Test (
pid INT PRIMARY KEY NOT NULL,
type CHAR NOT NULL,
data VARCHAR(10) NOT NULL
)

INSERT INTO #Test (pid, type, data)
SELECT 1, 'A', 'pizza' UNION ALL
SELECT 2, 'A', 'cake' UNION ALL
SELECT 3, 'A', 'spagetti' UNION ALL
SELECT 4, 'B', 'beer' UNION ALL
SELECT 5, 'B', 'rice' UNION ALL
SELECT 6, 'B', 'hammer'
----------------------------------------


What I'd like to get is the "data" associated whit the biggest "pid"
with "type" 'A': spaghetti.

I often face this kind of query and I'm always wondering if there is a
better way to do that. Here is the way I do this:


----------------------------------------
SELECT data
FROM #Test
WHERE pid = (SELECT TOP 1 pid FROM #Test WHERE type = 'A' ORDER BY pid
DESC)
----------------------------------------


I suspect this is not the more comprehensive way to do this. Anybody do
this differently?


Yannick
Re: Query question MC
11/30/2005 12:00:00 AM
Well, you could use max function if you think it looks better :). It is a
bit easier to read. You could test performance on both of these queries and
see if one performs any better then the other....

WHERE pid = (SELECT max(pid) FROM #Test WHERE type = 'A' )


MC


[quoted text, click to view]

Re: Query question Erland Sommarskog
11/30/2005 12:00:14 PM
Yannick Turgeon (vendredi5h@gmail.com) writes:
[quoted text, click to view]

Another variation:

SELECT a.data
FROM #Test a
JOIN (SELECT type, pid = MAX(pid)
FROM #Test
GROUP BY type) AS b ON a.type = b.type
AND a.pid = b.pid


--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
Re: Query question Yannick Turgeon
12/1/2005 12:03:03 PM
Ok. Thanks to both of you.

I think something like:

SELECT a.data
FROM #Test a
WHERE a.type = 'A'
GROUP BY a.type
HAVING pid = MAX(pid)

or even better:

SELECT a.data
FROM #Test a
WHERE a.type = 'A'
AND pid = MAX(pid)

would be a good functionnality (with MAX or any other aggregate
function) to add to transact/SQL or to SQL standard.

Yannick
Re: Query question Erland Sommarskog
12/1/2005 9:55:36 PM
Yannick Turgeon (vendredi5h@gmail.com) writes:
[quoted text, click to view]

Maybe. If it clear what it means. Which in at least in the second
case is not at all clear. MAX(pid) in the entire #Test? MAX(pid) for
type = 'A' or what?


--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
AddThis Social Bookmark Button