SQL 从多行中提取单行的查询

SQL query for extracting a single row from multiple rows

我们之前有一个 table 用于用户信息,其中也包含 pinHash

id userId seed assetType pinHash
1 110 a12H Bitcoin q23es
2 111 r23s Bitcoin e2w12
3 111 y36w Ethereum e2w12

因此,对于相同的 userId,所有 assetTypes 的 pinHash 都是相同的。

现在,我们正在迁移到另一个 table

id userId pinHash
1 110 q23es
2 111 e2w12

其中 SQL 可用于获取此迁移的所有记录,即具有 pinHash 的不同用户 ID。

N.B:我已经使用 spring 引导完成了此迁移,我从第一个 table 中获取所有行,然后使用 HashMap 仅将一行 userId 放入新 table。不过,我还是喜欢 SQL 结果只有不同的 userId 行。

假设您总是希望报告每组重复项中的最小值 id,我们可以在此处使用聚合:

SELECT MIN(id) AS id, userId, pinHash
FROM yourTable
GROUP BY userId, pinHash;

您的数据

CREATE TABLE TEST(
   id        INTEGER  NOT NULL 
  ,userId    INTEGER  NOT NULL
  ,seed      VARCHAR(5) NOT NULL
  ,assetType VARCHAR(9) NOT NULL
  ,pinHash   VARCHAR(5) NOT NULL
);
INSERT INTO TEST
(id,userId,seed,assetType,pinHash) VALUES 
(1,110,'a12H','Bitcoin','q23es'),
(2,111,'r23s','Bitcoin','e2w12'),
 (3,111,'y36w','Ethereum','e2w12');

使用Row_number函数

SELECT id,
       userid,
       pinhash
FROM   (SELECT id,
               userid,
               seed,
               assettype,
               pinhash,
               Row_number ()
                 OVER (
                   partition BY userid, pinhash
                   ORDER BY id ASC ) rn
        FROM   test) T
WHERE  rn = 1