我正在寻找一种很好的方法来执行以下操作:
我们有一个表Accounts
,其中一些记录被意外导入两次,因此它们是重复的。我发现我可以使用以下查询选择导入两次的所有行:
select name, vatnumber from Accounts
WHERE IsDeleted='false'
GROUP BY name, vatnumber
HAVING count(*) > 1
基本上:如果name
和vatnumber
相同,则它们是重复的。
这为我提供了两次导入的所有记录。现在我正在寻找一种方法来获得每个双记录的第一个Id,所以我可以做类似的事情:
UPDATE Accounts SET IsDeleted='true'
WHERE Id = (select id ...)
所以基本上,我正在尝试更新每个双记录的第一行,所以没有更多的双打。有谁能指出我正确的方向?除了做手工劳动之外,我还没有得到关于如何开始这样做的最微弱的线索,我猜测有一种更简单的方法。
示例数据:
Id VatNumber Name
1 BE10128292 Microsoft
2 BE99292200 Google
3 BE10128292 Microsoft
4 BE99292200 Some other company
5 BE99292200 Google
期望的结果:
Id VatNumber Name
1 BE10128292 Microsoft
2 BE99292200 Google
我是否真的获得了第一个Microsoft
或最后一个Microsoft
记录并不重要。理想情况下,它会是第一个。
答案 0 :(得分:3)
这应该完成工作,运行示例并检查输出。它会更新您的IsDeleted
标记,其中包含重复项,但仅使用MIN(ID)
定位第一行。
CREATE TABLE #dupes
(
id INT,
vatNo NVARCHAR(20),
name NVARCHAR(20),
isDeleted BIT
DEFAULT 0
);
INSERT INTO #dupes
(
id,
vatNo,
name
)
VALUES
(1, 'BE10128292', 'Microsoft'),
(2, 'BE99292200', 'Google'),
(3, 'BE10128292', 'Microsoft'),
(4, 'BE99292200', 'Some other company'),
(5, 'BE99292200', 'Google');
UPDATE #dupes
SET isDeleted = 1
WHERE id IN (
SELECT MIN(id) MinId
FROM #dupes
WHERE isDeleted = 0
GROUP BY name,
vatNo
HAVING COUNT(*) > 1
);
SELECT *
FROM #dupes AS d;
DROP TABLE #dupes;
<强>产地:强>
id vatNo name isDeleted
1 BE10128292 Microsoft 1
2 BE99292200 Google 1
3 BE10128292 Microsoft 0
4 BE99292200 Some other company 0
5 BE99292200 Google 0
特定于您的数据库,查询将是:
UPDATE Accounts
SET isDeleted = 1
WHERE Id IN (
SELECT MIN(id) MinId
FROM Accounts
WHERE isDeleted = 0
GROUP BY name,
vatNo
HAVING COUNT(*) > 1
);
答案 1 :(得分:2)
使用CTE
:
;WITH cte
AS (
SELECT *,
ROW_NUMBER() OVER(PARTITION BY vatnumber ORDER BY id) rn
FROM <tablename>)
SELECT Id,
VatNumber,
Name
FROM cte
WHERE rn = 1;
期望的结果:
Id VatNumber Name
1 BE10128292 Microsoft
2 BE99292200 Google
答案 2 :(得分:1)
检查这个。
button span{
padding-left: 10px;
transition: .2s;
}
button span:hover{
padding-left: 20px;
}
检查演示Here
答案 3 :(得分:1)
尝试CTE
,如下所示:
WITH CTE
AS (
SELECT vatnumber,
name,
ROW_NUMBER() OVER(PARTITION BY vatnumber,
name ORDER BY ID) rowid,
IsDeleted
FROM Accounts
WHERE IsDeleted = 'false')
UPDATE CTE
SET
IsDeleted = 'true'
WHERE rowid > 1;
答案 4 :(得分:0)
试试这个,
//Set Access Token
$access = base64_encode($str);
//Set Header Request Data
$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: Basic'." ".$access;
//Initiate GET Request via curl
$ch=curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
curl_setopt($ch, CURLOPT_URL, $apiurl );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
//Close the curl list
curl_close($ch);
//Output the Response
$data = json_decode($result, true);