Click here to Skip to main content
16,020,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear Sir

I have a following table in SQL Server. I want to write a query in such a way that each time i run the query it will display one record from each 'Type' randomly. I mean when i run the query it should display one record from 'fruit' type and one record from 'cold drinks' type. But every time it should display records randomly.

product
--------

id type name
--- ----- ------
1 fruits orange
2 cold drinks Coca-cola
3 cold drinks mirinda
4 fruits banana
5 fruits apple
6 fruits grapes


kindly help me Sir.


Sashibhusan Meher
Posted

Make two columns of fruit and colddrinks separately and fire following Query to get random values.

SQL
SELECT TOP 1 fruit, colddrinks FROM product ORDER BY NEWID()
 
Share this answer
 
Comments
RaviRanjanKr 12-Dec-11 7:32am    
My 5+
Sashibhusan Meher 12-Dec-11 7:38am    
Sorry sir, it will not work. Because i want to display all the field from the table. And i cann't create separate column for all the Product Types. So please give me another solution if u can..

thank you
Here it is :

SQL
IF OBJECT_ID(N'tempdb..#pr') IS NOT NULL
  drop table #pr
  
select  ID, [type] , name , abs(CHECKSUM(NewId()))   rnd   into #pr from   product

;with a(t , mr) as
(
select type, MAX(rnd) rnd from #pr group by type
)
select p.id, p.type, p.name from a inner join #pr p on a.t = p.type and a.mr = p.rnd


It was impossible to avoid temporary tables because the random field was regenerated in joins and ruined all of my plans so I went for a temporary table.

Good Luck
 
Share this answer
 
If you'd like to display a random record, try this up!

SQL
SELECT TOP 1 * FROM product
ORDER BY NEWID()


That should do it.

Regards,
Eduard
 
Share this answer
 
Comments
[no name] 12-Dec-11 23:31pm    
oops didn't see, it's almost the same with solution1.
Sashibhusan Meher 13-Dec-11 1:55am    
thank you sir.. But i also want that the query should retrieve one record from each type randomly. For Example if the table has two product type query should show two records in a single execution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900