Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
RichardSteele
Posting Yak Master
160 Posts |
Posted - 2008-05-19 : 17:21:19
|
| Here's my query:Select portfolio, custnumber from table some custnumbers are the same. However I only want the query to include one portfolio per custnumber, ideally the first portfolio.How would I accomplish this? Many thanks! |
|
|
tkizer
Almighty SQL Goddess
38200 Posts |
Posted - 2008-05-19 : 17:23:18
|
| SELECT MIN(portfolio), custnumberFROM tableGROUP BY custnumberTara KizerMicrosoft MVP for Windows Server System - SQL Serverhttp://weblogs.sqlteam.com/tarad/Database maintenance routines:http://weblogs.sqlteam.com/tarad/archive/2004/07/02/1705.aspx |
 |
|
|
RichardSteele
Posting Yak Master
160 Posts |
Posted - 2008-05-19 : 18:45:23
|
| Great, thanks. Now is there a way to randomize the portfolio that is retrieved for a particular custnumber while keeping the custnumber distinct? |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-05-20 : 00:01:15
|
quote: Originally posted by RichardSteele Great, thanks. Now is there a way to randomize the portfolio that is retrieved for a particular custnumber while keeping the custnumber distinct?
If you're using sql 2000:-declare @temp table(id int identity (1,1),customerno int,portfolio varchar(20),other fields...) insert into @temp (customerno,portfolio,...)select customerno,portfolio,otherfields,...from yourtable order by newid()select t1.* from @temp t1inner join (select customerno,min(id) as minid from @temp group by customerno)t2on t2.customerno=t1.customernoand t1.id=t2.minid if in sql 2005:-SELECT *FROM(SELECT ROW_NUMBER OVER(PARTITION BY customerno ORDER BY newid()) AS RowNo,*FROM YourTable)tWHERE t.RowNo=1 |
 |
|
|
RichardSteele
Posting Yak Master
160 Posts |
Posted - 2008-05-20 : 04:13:03
|
| Thank you so much! That row_number() function is a fantastic new feature of 2005! |
 |
|
|
RichardSteele
Posting Yak Master
160 Posts |
Posted - 2008-05-20 : 04:40:59
|
| One last question, can I use an inner join in this new sql 2005 query? I want to pull the customer's name from another table that also has a key field custnumber. |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-05-20 : 05:18:35
|
quote: Originally posted by RichardSteele One last question, can I use an inner join in this new sql 2005 query? I want to pull the customer's name from another table that also has a key field custnumber.
yup you can. Just inner join to your other table based on linking column. Are you sure you dont have multiple records in other table for same linking column value? in which case the data will still duplicate. |
 |
|
|
RichardSteele
Posting Yak Master
160 Posts |
Posted - 2008-05-20 : 10:58:10
|
| Thanks! Got it! |
 |
|
|
|
|
|
|
|