Wrox Programmer Forums
Go Back   Wrox Programmer Forums > SQL Server > SQL Server 2005 > SQL Server 2005
|
SQL Server 2005 General discussion of SQL Server *2005* version only.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the SQL Server 2005 section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old August 15th, 2007, 08:36 PM
Authorized User
 
Join Date: Nov 2005
Posts: 51
Thanks: 0
Thanked 0 Times in 0 Posts
Default Return one record per value

My select statement returns two columns, ContactID and IndividualID. Any given IndividualID will have 1 or more ContactID. In the cases where there is more than one, how can it return only 1 ContactID per IndividualID? It doesn't matter if it's always the first ContactID per IndividualID or a random one.
 
Old August 16th, 2007, 03:51 PM
Friend of Wrox
 
Join Date: May 2006
Posts: 246
Thanks: 0
Thanked 0 Times in 0 Posts
Default

SELECT IndividualID, MAX(ContactID) FROM Table1 GROUP BY IndividualID ORDER BY IndividualID


 
Old August 16th, 2007, 06:16 PM
Authorized User
 
Join Date: Nov 2005
Posts: 51
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Aw geez, that was easy. Thank you very much! How about making it pick a random one for bonus points?
 
Old August 17th, 2007, 03:04 AM
Friend of Wrox
 
Join Date: May 2006
Posts: 246
Thanks: 0
Thanked 0 Times in 0 Posts
Default

It's doable, but takes a lot of resources from the server.

SELECT i.IndividualID, (SELECT TOP 1 t.ContactID FROM Table1 AS t WHERE t.IndividualID = i.IndividualID ORDER BY NEWID())
FROM (SELECT IndividualID FROM Table1 GROUP BY IndividualID) AS i


 
Old August 17th, 2007, 09:31 PM
Authorized User
 
Join Date: Nov 2005
Posts: 51
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Would making it do this via a function or stored procedure be too much to ask (I know you can't call NEWID in a function)?





Similar Threads
Thread Thread Starter Forum Replies Last Post
Return a record that doesn't exist in a table? Unregistered SQL Server 2000 4 May 3rd, 2006 01:27 AM
return record count by quarter jtyson SQL Server 2000 1 June 29th, 2004 11:24 PM
Return the last record altered MikeJames42 VB How-To 1 February 13th, 2004 12:57 PM
Return a Record set into a table? morpheus Classic ASP Basics 2 November 18th, 2003 11:38 AM
Forms -- how to return to the same record and fiel tcarnahan Access 1 June 10th, 2003 11:24 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.