我需要根据表中的行数和名为' users'的表中的用户数,将一个表中相同数量的记录插入另一个表中。例如,如果一个表'退款_上传'有100条记录和表'用户'有10个用户,然后我想将所有100行插入表格'退款'并为每个UserID分配10条记录。
目前,我只是这样做
INSERT Refunds
(BorrowerNumber, UserID)
SELECT BorrowerNumber, 'unknown' FROM Refunds_Upload
这是需要发生什么的概述
--get the list of users from the Users table
SELECT UserID FROM Users
--determine how many refunds each user gets
Declare @RefundsPerUser int
SET @RefundsPerUser = ROUND((SELECT COUNT(*) FROM Users) / (SELECT COUNT(*) FROM Refunds_Upload),2)
--For each UserID in Step 1...
INSERT INTO Refunds @RefundsPerUser INTO Refunds
答案 0 :(得分:0)
我不能说你在做什么是有道理的,但是你会怎么做:
WITH refund_amt(amt) AS
(
SELECT ROUND(COUNT(*)/MAX(RU.C),2) AS AMT
FROM Users
CROSS JOIN (SELECT COUNT(*) AS C FROM Refunds_Upload) RU
)
INSERT INTO Refunds (BorrowerNumber, UserID)
SELECT UserID, refund_amt.amt
FROM Users
CROSS JOIN refund_amt