INSERT INTO table is producing a NULL value for the returned recordset. I'm trying to add the SUM(m.earnings + m.fpearn) from pfinancial table and userid & minpay from the userbase table.
What am I doing wrong? Also is there a better way to reiterate through the temp table of id's ?
From the tables below I should populate the publsher_monthly table with one unique id per userid, the minpay amount from the userbase and the sum of the m.earnings + m.fpearn columns from the pfinancial table
publisher_monthly table
pmuseris pmminpay pmearnings
5 20 75
6 30 27
userbase table
userid minpay
5 20
6 30
pfinancial table
userid earnings fpearn
5 10 30
5 20 15
6 15 12
My query:
DECLARE @realuserid bigint
CREATE TABLE #tmppmuserids(
idx bigint Primary Key IDENTITY(1,1),
tmppmuserid bigint NULL
)
INSERT INTO #tmppmuserids
SELECT DISTINCT userid FROM pfinancial
DECLARE @i bigint
DECLARE @numrows bigint
SET @i = 1
SET @numrows = (SELECT COUNT(*) FROM #tmppmuserids)
IF @numrows > 0
WHILE (@i <= (SELECT MAX(idx) FROM #tmppmuserids))
BEGIN
SET @realuserid = (SELECT tmppmuserid FROM #tmppmuserids WHERE idx = @i)
--PROBLEM HERE
INSERT INTO publisher_monthly (pmearnings, pmuserid, pmminpay)
SELECT
SUM(m.earnings + m.fpearn), MAX(@realuserid), MAX(u.minpay)
FROM pfinancial m
INNER JOIN userbase u on u.userid = m.userid
WHERE
m.userid = @realuserid AND
(m.created >= DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE()),0)) AND
(m.created < DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE()) + 1, 0))
--END PROBLEM
SET @i = @i + 1
END
SELECT * FROM #tmppmuserids
SELECT * FROM publisher_monthly
DROP TABLE #tmppmuserids