在SQL Server 2008中填充表时对两列使用SUM函数时返回空值
INSERT INTO table正在为返回的记录集生成空值。我试图从pffinancial表中添加SUMm.earnings+m.fpearn,从userbase表中添加userid&minpay 我做错了什么?还有没有更好的方法通过id的临时表进行重申 从下表中,我应该使用每个用户id的一个唯一id、来自用户库的minpay金额和来自PFFinancial表的m.Incomes+m.fpearn列的总和填充publsher_monthly表 出版商月刊表 用户基表 p财务表 我的问题是:在SQL Server 2008中填充表时对两列使用SUM函数时返回空值,sql,sql-server-2008,tsql,sql-server-2005,Sql,Sql Server 2008,Tsql,Sql Server 2005,INSERT INTO table正在为返回的记录集生成空值。我试图从pffinancial表中添加SUMm.earnings+m.fpearn,从userbase表中添加userid&minpay 我做错了什么?还有没有更好的方法通过id的临时表进行重申 从下表中,我应该使用每个用户id的一个唯一id、来自用户库的minpay金额和来自PFFinancial表的m.Incomes+m.fpearn列的总和填充publsher_monthly表 出版商月刊表 用户基表 p财务表 我的问题是: D
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
在其周围放置一个IsNull:
SELECT SUM(IsNull(m.earnings, 0) + IsNull(m.fpearn, 0))
甚至围绕整个事件:
SELECT IsNull(SUM(m.earnings + m.fpearn), 0)
在返回的值周围放置一个ISNULL会有什么帮助?问题在于返回的是空值。我从中获取数据的列不是空的,但不知何故返回的记录集是空的。我的问题出了点问题。我需要修正这个问题。你应该发布一些样本数据,然后提供一个更清晰的问题图片。只是添加了样本数据。忘了做那件事。对不起,我刚刚使用了您的示例数据和查询,没有得到空结果。数据正在正确加载到publisher_monthly表中。当然,我的数据中没有您创建的字段,所以问题可能就在这里。+1表示在整个表达式周围使用ISNULL,并轻推到10k代表,欢迎加入俱乐部!ツ
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
SELECT SUM(IsNull(m.earnings, 0) + IsNull(m.fpearn, 0))
SELECT IsNull(SUM(m.earnings + m.fpearn), 0)