需要查询帮助:
Id Name Balance
1 A 10
2 A -10
3 A 10
4 A 15
5 B 10.5
6 B -10.5
7 B 25
要求:我想删除每个名称的+ ve和-ve值的余额。我期待以下输出
预期结果: -
Id Name Balance
1 A 10
2 A 15
3 B 25
请与我分享SQL查询。
答案 0 :(得分:0)
这是一种方法。
创建用于测试的虚拟数据
CREATE TABLE foo (Id INT, Name VARCHAR(50), Balance money);
INSERT INTO foo VALUES (1, 'A', 10);
INSERT INTO foo VALUES (2, 'A', -10);
INSERT INTO foo VALUES (3, 'A', 10);
INSERT INTO foo VALUES (4, 'A', 15);
INSERT INTO foo VALUES (5, 'B', 10.5);
INSERT INTO foo VALUES (6, 'B', -10.5);
INSERT INTO foo VALUES (7, 'B', 25);
1)创建一个临时表,其中有一个额外的MatchFound列来记录是否找到匹配。
CREATE TABLE #TempTable(Id int, Name varchar(50), Balance decimal(10,2), MatchFound bit);
INSERT INTO #TempTable (Id, Name, Balance, MatchFound)
SELECT Id, Name, Balance, 0
FROM foo;
2)遍历数据以查找每行的匹配项。如果找到匹配项,请更新MatchFound列。
DECLARE @Id INT, @Name VARCHAR(50), @Balance decimal(10,2), @MatchId INT;
DECLARE MyCursor CURSOR FOR SELECT Id, Name, Balance FROM #TempTable ORDER BY Id;
OPEN MyCursor
FETCH NEXT FROM MyCursor INTO @Id, @Name, @Balance
WHILE @@FETCH_STATUS = 0
BEGIN
IF EXISTS (SELECT 1 FROM #TempTable WHERE Id = @Id AND MatchFound = 0)
BEGIN
SET @MatchId = NULL
SELECT TOP 1 @MatchId = Id FROM #TempTable
WHERE Id <> @Id AND Name = @Name AND Balance = @Balance * -1 AND MatchFound = 0
IF @MatchId IS NOT NULL
UPDATE #TempTable SET MatchFound = 1 WHERE Id IN (@Id, @MatchId)
END
FETCH NEXT FROM MyCursor INTO @Id, @Name, @Balance
END
CLOSE MyCursor;
DEALLOCATE MyCursor;
3)选择并返回没有匹配的行
Select Id, Name, Balance From #TempTable Where MatchFound = 0
4)清理
drop table #TempTable