合并重复记录并更新其表

时间:2015-10-15 05:50:56

标签: sql-server

你能帮我解决SQL Query的问题吗?

我想合并/(必要时加总)customer的所有数据与重复的客户名称。

在我的项目中,我已经找到了使用此代码复制的所有客户:

select Firstname, Lastname, count(1) as RepeatedCount 
from customer
group by FirstName, LastName
having count(1) > 1

如何仅使用1条客户记录更新Customer表,并仅在一条记录中获得totalsalestotavisits的总和。

示例数据:

FirstName  LastName   TotalSales     TotalVisits
---------- ---------- -------------- -----------
Michelle   Go         0.00           0
Michelle   Go         6975.00        1
Michelle   Go         1195.00        1
Michelle   Go         9145.00        3
Michelle   Go         57785.00       5
Michelle   Go         5845.00        1
Michelle   Go         0.00           0
Michelle   Go         0.00           0

预期产出:

FirstName  LastName   TotalSales     TolalVisits
---------- ---------- -------------- -----------
Michelle   Go         80945.00       11

3 个答案:

答案 0 :(得分:1)

您已将聚合函数SUMGROUP BY一起使用。

<强>查询

SELECT FirstName,LastName,
SUM(totalsales) as totalsales,
SUM(totalvisits) as totalvisits
FROM customer
GROUP BY FirstName,LastName;

为了更好的练习,我建议您为customerId添加一个独特的列 这样你就可以轻松地将它分组。

SQL Fiddle

答案 1 :(得分:0)

您可以使用SUMGROUP BY并将结果插入临时表中。

IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL
    DROP TABLE #tempTable

SELECT
    c.FirstName,
    c.LastName,
    SUM(c.TotalSales) AS TotalSales,
    SUM(c.TotalVisits) AS TolalVisits
INTO #tempTable
FROM Customer c
GROUP BY c.LastName, c.FirstName

TRUNCATE原始表格,CustomerINSERT #tempTable的数据:

TRUNCATE TABLE Customer
INSERT INTO Customer
    SELECT * FROM #tempTable

答案 2 :(得分:0)

让我们在下面将CTE视为主要表格。

;WITH user_details
AS
(
    SELECT 'Michelle' AS FirstName,'Go' AS LastName,0.00 AS totalsales,0 AS totalvists
UNION
    SELECT 'MICHELLE','GO',6975.00,1
UNION
    SELECT 'michelle','go',1195.00,1
UNION
    SELECT 'michelle','go',9145.00,3
UNION
    SELECT 'MICHELLE','GO',57785.00,5
UNION
    SELECT 'MICHELLE','GO',5845.00,1
UNION
    SELECT 'Michelle','Go',0.00,0
UNION
    SELECT 'Michelle','Go',0.00,0
)
  

使用聚合函数对查询进行分组并插入临时表

SELECT 
    FirstName,
    LastName,
    SUM(totalsales)   [totalsales],
    SUM([totalvists]) [totalvisits]
INTO
    #temp
FROM
    user_details
GROUP BY
    FirstName,
    LastName

-- select * from #temp
  

截断主表

TRUNCATE TABLE user_details
  

现在再次将更新的记录插入新表

INSERT INTO user_details (FirstName,LastName,totalsales,totalvisits -- Main table
SELECT
    FirstName,
    LastName,
    totalsales,
    totalvisits
FROM
    #temp