我是新手。 我有一个存储User_id的table1和另一个存储data_id的table2 将从table2中随机选择Data_id,并且所有user_id都应具有所有随机data_id。
table1 table2
user1 data1
user2 data2
user3 data3
user4 data4
user5 data5
我想从table2获取3个随机数据,并将这些数据与user_id #s一起写入table3 它应该如下所示
table3
user1 data2
user1 data3
user1 data4
user2 data2
user2 data3
user2 data4
user3 data2
user3 data3
user3 data4
user4 data2
user4 data3
user4 data4
user5 data2
user5 data3
user5 data4
答案 0 :(得分:0)
假设您希望每个用户使用相同的3个随机data_id值,则一个方法使用CROSS APPLY
:
CREATE TABLE dbo.table1 ( user_id varchar(10) NOT NULL )
INSERT INTO dbo.table1
VALUES ( 'user1' )
, ( 'user2' )
, ( 'user3' )
, ( 'user4' )
, ( 'user5' );
CREATE TABLE dbo.table2 ( data_id varchar(10) NOT NULL );
INSERT INTO dbo.table2
VALUES ( 'data1' )
, ( 'data2' )
, ( 'data3' )
, ( 'data4' )
, ( 'data5' );
SELECT user_id
, data_id
FROM dbo.table1
CROSS APPLY ( SELECT TOP ( 3 )
data_id
FROM dbo.table2
ORDER BY NEWID()
) AS table2
ORDER BY user_id
, data_id;
答案 1 :(得分:0)
基于@Dan Guzman回答我认为它已经参考并重新修改了答案。如果它适合您,请检查并告诉我
declare @table1 TABLE ( user_id varchar(10) NOT NULL )
INSERT INTO @table1
VALUES ( 'user1' )
, ( 'user2' )
, ( 'user3' )
, ( 'user4' )
, ( 'user5' );
declare @table2 TABLE ( data_id varchar(10) NOT NULL );
INSERT INTO @table2
VALUES ( 'data1' )
, ( 'data2' )
, ( 'data3' )
, ( 'data4' )
, ( 'data5' );
;with cte as (
SELECT user_id
, data_id
FROM @table1
, ( SELECT TOP ( 4 )
data_id
FROM @table2
ORDER BY data_id
) AS table2
)
Select A.user_id,A.data_id from (
select c.user_id,
c.data_id,
ROW_NUMBER()OVER(PARTITION BY c.user_id ORDER BY c.user_id,c.data_id) RN
from cte C
)A
where A.Rn <> 1