I’m using SQL Server 2008, I want select random row record, and the total number of record is depend on another table’s column value, how to do this?
My SQL statement is something like this, but wrong..
select top b.number a.name, a.link_id
from A a
left join B b on b.link_id = a.link_id
order by newid()
Here are my tables and the expected result.
Table A:
name link_id
james 100
albert 100
susan 100
simon 101
tom 101
fion 101
Table B:
link_id number
100 2
101 1
Expected result:
-
when run 1st time, result may be:
name link_id james 100 susan 100 fion 101 -
2nd time result may be:
albert 100 susan 100 simon 101 -
3rd time could be:
james 100 albert 100 fion 101
Explaination
Refer to table B, link_id: 100, number: 2
meaning that Table A should select out 2 random record for link_id = 100
and need to select 1 random record for link_id=101
You can use the ROW_NUMBER() function:
Here is a SqlFiddle to show this in action: http://sqlfiddle.com/#!3/92eac/2