简体   繁体   中英

NULL value returned when using SUM function on two columns while populating table in SQL Server 2008

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

Place an IsNull around them:

SELECT SUM(IsNull(m.earnings, 0) + IsNull(m.fpearn, 0))

or even around the whole thing:

SELECT IsNull(SUM(m.earnings + m.fpearn), 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM