表格1
Rowno name Date
------------------------------------
1 sathish Dec 21
2 kumar Dec 22
3 sathish Dec 21
4 sathish Dec 22
5 sathish Dec 21
5 sathish Dec 22
表2
Date NoofTran
-----------------------
Dec22 2
Dec21 1
我想table1
根据table2
nooftran
值随机获取记录。
在12月22日,表2中的交易次数为2,因此有两条记录应该在相应的日期从表1中获取该记录,并且应该是随机情况。因此,在12月22日的3条记录中,有2条应该随机出现。
我应该使用什么SQL查询?
如果您使用的是SQL Server,则可以像这样使用交叉应用
select t1.*
from Table2 as t2
cross apply
(
select top (select T2.nooftran) *
from Table1 as t1
where t2.Date = t1.date
order by newid()
) as t1
declare @T1 table (rowno int, name varchar(max), [date] date);
declare @T2 table ([date] date, nooftran int);
insert into @T1 values
(1, 'sathish', '2015-01-01'),
(2, 'kumar', '2016-01-01'),
(3, 'sathish', '2015-01-01'),
(4, 'sathish', '2016-01-01'),
(5, 'sathish', '2015-01-01'),
(5, 'sathish', '2016-01-01');
insert into @T2 values ( '2016-01-01', 2), ( '2015-01-01', 1);
select t1.*
from @T2 as t2
cross apply
(
select top (select T2.nooftran) *
from @T1 as t1
where t2.Date = t1.date
order by newid()
) as t1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句