提取具有一列不同值的记录,同时在多条记录时替换另一列的值

时间:2018-08-24 20:57:26

标签: db2

我需要基于不同的rid联接2个表,同时用多行中的不同值替换列值。通过下面的示例可以更好地说明。

CREATE TABLE usr (rid INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(12) NOT NULL,
email VARCHAR(20) NOT NULL);

CREATE TABLE usr_loc
(rid INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
code CHAR NOT NULL PRIMARY KEY,
loc_id INT NOT NULL PRIMARY KEY);

INSERT INTO usr VALUES 
(1,'John','john@product'),
(2,'Linda','linda@product'),
(3,'Greg','greg@product'),
(4,'Kate','kate@product'),
(5,'Johny','johny@product'),
(6,'Mary','mary@test');

INSERT INTO usr_loc VALUES 
(1,'A',4532),
(1,'I',4538),
(1,'I',4545),
(2,'I',3123),
(3,'A',4512),
(3,'A',4527),
(4,'I',4567),
(4,'A',4565),
(5,'I',4512),
(6,'I',4567);
(6,'I',4569);

必需的结果集

+-----+-------+------+-----------------+
| rid | name  | Code |      email      |
+-----+-------+------+-----------------+
|   1 | John  | B    | 'john@product'  |
|   2 | Linda | I    | 'linda@product' |
|   3 | Greg  | A    | 'greg@product'  |
|   4 | Kate  | B    | 'kate@product'  |
|   5 | Johny | I    | 'johny@product' |
|   6 | Mary  | I    | 'mary@test'     |
+-----+-------+------+-----------------+

我曾尝试过加入一些查询,有些却算在内,但由于完全满足整个情况而丢失了。

我想到的查询是

SELECT distinct(a.rid)as rid, a.name, a.email, 'B' as code 
FROM usr 
JOIN usr_loc b ON a.rid=b.rid 
WHERE a.rid IN (SELECT rid FROM usr_loc GROUP BY rid HAVING COUNT(*) > 1);`

1 个答案:

答案 0 :(得分:0)

您需要按用户分组并计算在usr_loc中发生的次数。如果不止一个,则将code替换为B。见下文:

select
    rid,
    name,
    case when cnt > 1 then 'B' else min_code end as code,
    email
  from (
    select u.rid, u.name, u.email, min(l.code) as min_code, count(*) as cnt
      from usr u
      join usr_loc l on l.rid = u.rid
      group by u.rid, u.name, u.email
  ) x;

在我看来您正在使用MySQL,而不是IBM DB2。是吗?