SQL Server SQL语句 - 更新记录

时间:2016-12-02 10:19:45

标签: sql sql-server tsql

我有如下数据:

enter image description here

我需要使用Matching_id更新Matching_Typecolumn id, region, company, dept, subdept and amountsepend。逻辑是:

Sum AmountSepend by Region, Company, Dept and SubDept。如果总和为0,那么匹配_类型是匹配'和Matching_id是匹配记录的ID的组合,否则不匹配'和Matching_id是id。 ** SUM表示相同标准的所有记录的总和,无论AmountSepend是正数还是负数。

另一个重要标准是,如果交易是单一记录,则表示按地区,公司,部门和SubDept分组的总计数为1,则匹配类型为不匹配且匹配_UID为id,无论AmountSepend为0还是正/负值。示例id 8.

以下是输出:

enter image description here

这里有表格和数据脚本

CREATE TABLE [dbo].[StackoverflowQuest](
[id] [int] NOT NULL,
[Region] [varchar](50) NULL,
[Company] [varchar](50) NULL,
[Dept] [varchar](50) NULL,
[SubDept] [varchar](50) NULL,
[AmountSepend] [float] NULL,
[Matching_id] [varchar](100) NULL,
[Matching_Type] [varchar](100) NULL
) ON [PRIMARY]

我怎么能取得这样的结果?任何帮助/提示都将不胜感激

1 个答案:

答案 0 :(得分:0)

CREATE TABLE #Table(Id INT,Region VARCHAR(100),Company INT,Dept INT,SubDept       
INT,AmtSpend INT,MatchingId VARCHAR(100),MatchingType VARCHAR(100))

INSERT INTO #Table(Id ,Region ,Company , Dept  ,SubDept ,AmtSpend )
SELECT 1,'NAM',12378,1,NULL,900 UNION ALL
SELECT 2,'NAM',12378,1,NULL,-900 UNION ALL
SELECT 3,'NAM',12370,1,23,1000 UNION ALL
SELECT 4,'ASA',1234,9,12,5000 UNION ALL
SELECT 5,'NAM',12370,1,23,-1000 UNION ALL
SELECT 6,'ASA',1234,9,12,800 UNION ALL
SELECT 7,'ASA',1234,9,12,-600 UNION ALL
SELECT 8,'ASA',12311,6,NULL,200

UPDATE #Table SET MatchingId = MatchIds,MatchingType = 'Match'
FROM 
(
  SELECT T2.Company,STUFF( ( SELECT ',' + CAST(T3.Id AS VARCHAR) FROM #Table    
  T3 WHERE T2.Company = T3.Company FOR XML PATH('')),1,1,'') MatchIds
  FROM #Table T2
  JOIN 
    (
    SELECT T1.Company Company,SUM(T1.AmtSpend) Total
    FROM #Table T1
    GROUP BY T1.Company
    HAVING SUM(T1.AmtSpend) = 0
  )A ON A.Company = T2.Company
    GROUP BY T2.Company
 ) A 
WHERE A.Company = #Table.Company


UPDATE #Table SET MatchingId = CAST(Id AS VARCHAR),MatchingType = 'Not  
Match' WHERE ISNULL(MatchingId,'') = ''

SELECT * FROM #Table