将两个记录合并为一个

时间:2013-02-20 10:25:58

标签: sql-server stored-procedures coalesce

我有一个存储两个值的表;每个客户的“总计”和“欠款”。数据使用两个文件上传到表中,一个文件带来'total',另一个带来'due'。这意味着每个customerID都有两条记录:

customerID:--------Total:--------- Owing:

1234----------------  1000----------NULL

1234-----------------NULL-----------200

我想编写一个将两个记录合并在一起的存储过程:

customerID:--------Total:--------- Owing:

1234----------------  1000----------200

我见过使用COALESCE的例子,所以把这样的东西放在一起:

BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

--Variable declarations

DECLARE @customer_id varchar(20)
DECLARE @total decimal(15,8)
DECLARE @owing decimal(15,8)
DECLARE @customer_name_date varchar(255)
DECLARE @organisation varchar(4)
DECLARE @country_code varchar(2)
DECLARE @created_date datetime

--Other Variables
DECLARE @totals_staging_id int

--Get the id of the first row in the staging table
SELECT @totals_staging_id = MIN(totals_staging_id)
from TOTALS_STAGING

--iterate through the staging table
WHILE @totals_staging_id is not null
BEGIN

update TOTALS_STAGING

SET 
total = coalesce(@total, total),
owing = coalesce(@owing, owing)

where totals_staging_id = @totals_staging_id

END
END

任何想法?

4 个答案:

答案 0 :(得分:1)

SELECT t1.customerId, t1.total, t2.owing FROM test t1 JOIN test t2 ON ( t1.customerId = t2.customerId) WHERE t1.total IS NOT NULL AND t2.owing IS NOT NULL

想知道为什么不在第二次执行文件时使用UPDATE

答案 1 :(得分:0)

  

除COUNT外,聚合函数忽略空值。骨料   函数经常与SELECT的GROUP BY子句一起使用   声明。 MSDN

所以你不需要担心求和的空值。以下将为您的合并记录Fiddle-demo

select customerId,
       sum(Total) Total,
       sum(Owing) Owing
from T
Group by customerId

答案 2 :(得分:0)

试试这个:

CREATE TABLE #Temp
(
  CustomerId int,
  Total int,
  Owing int
)

insert into #Temp
values (1024,100,null),(1024,null,200),(1025,10,null)



Create Table #Final 
(
  CustomerId int,
  Total int,
  Owing int
)

insert into #Final
values (1025,100,50)



MERGE #Final AS F
USING 
(SELECT customerid,sum(Total) Total,sum(owing) owing FROM #Temp
 group by #Temp.customerid
) AS a

ON (F.customerid = a.customerid)
WHEN MATCHED THEN UPDATE SET F.Total = F.Total + isnull(a.Total,0)
                              ,F.Owing = F.Owing + isnull(a.Owing,0)
WHEN NOT MATCHED THEN
INSERT (CustomerId,Total,Owing)
VALUES (a.customerid,a.Total,a.owing);

select * from #Final

drop table #Temp
drop table #Final

答案 3 :(得分:0)

这应该有效:

SELECT CustomerID, 
       COALESCE(total1, total2) AS Total, 
       COALESCE(owing1, owing2) AS Owing
FROM 
(SELECT row1.CustomerID AS CustomerID,
        row1.Total AS total1,
        row2.Total AS total2,
        row1.Owing AS owing1,
        row2.Owing AS owing2
FROM YourTable row1 INNER JOIN YourTable row2 ON row1.CustomerID = row2.CustomerID
WHERE row1.Total IS NULL AND row2.Total IS NOT NULL) temp
--Note:  Alter the WHERE clause as necessary to ensure row1 and row2 are unique.

...但请注意,您需要一些机制来确保row1和row2是唯一的。我的WHERE子句是基于您提供的数据的示例。您需要调整此项以添加更符合业务规则的内容。

相关问题