how to randomly select a row from a table having more then one row with same id

Hi all,

I have a table Employee having columns as EmpId , EmpName and ProjectName. An Employee can be involved in more than one project, So the table structure is as below:

EmpId EmpName ProjectName

1 jane P1
1 jane p2
1 jane p3
2 david p1
2 david p4

Now I want that randomly one row should be retrieve from the table against a particular EmpId.

How could I do that?

Thanks in Advance!!!!!!!!
[758 byte] By [meenakshi_joshi09] at [2007-11-20 10:45:52]
# 1 Re: how to randomly select a row from a table having more then one row with same id
You will have to use a WHERE clause.

SELECT * FROM table WHERE EmpId = '1' AND ProjectName = 'p2'
PeejAvery at 2007-11-9 13:45:35 >
# 2 Re: how to randomly select a row from a table having more then one row with same id
If you are using MSSQL this would do the trick:
SELECT TOP 1 * FROM table WHERE EmpId = '1' ORDER BY NEWID()
millepag at 2007-11-9 13:46:35 >
# 3 Re: how to randomly select a row from a table having more then one row with same id
For MySQL, you'd use:
SELECT * FROM table
WHERE id = 1
ORDER BY RAND()
LIMIT 1;
andreasblixt at 2007-11-9 13:47:33 >
# 4 Re: how to randomly select a row from a table having more then one row with same id
Finally, If you're using Oracle you should write:

SELECT *
FROM table
WHERE id = 1
AND ROWNUM = 1

ROWNUM is a pseudo-column of recordsets, and it enumerates the selected rows.
davide++ at 2007-11-9 13:48:39 >
# 5 Re: how to randomly select a row from a table having more then one row with same id
SELECT * FROM table
WHERE id = 1
ORDER BY RAND()
LIMIT 1;
technoroj at 2007-11-9 13:49:38 >
# 6 Re: how to randomly select a row from a table having more then one row with same id
Finally, If you're using Oracle you should write:

ROWNUM is a pseudo-column of recordsets, and it enumerates the selected rows.

I think you'll find you have to randomize the rows order too:

SELECT * FROM
(
SELECT *
FROM table
WHERE id = 1
ORDER BY dbms_random.value
)
WHERE ROWNUM = 1
cjard at 2007-11-9 13:50:38 >
# 7 Re: how to randomly select a row from a table having more then one row with same id
You can check this blog post (from my blog) about returning random records from MS SQL Server and MySQL:
Returning random records.. MS SQL Server vs. MySQL ( http://forloveofsoftware.blogspot.com/2007/03/returning-randon-records-ms-sql-server.html)
hspc at 2007-11-9 13:51:43 >