0

I have 2 tables that I need to join based on distinct rid while replacing the column value with having different values in multiple rows. Better explained with an example set below.

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);

Required Result Set

+-----+-------+------+-----------------+
| 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'     |
+-----+-------+------+-----------------+

I have tried some queries to join and some to count but lost with the one which exactly satisfies the whole scenario.

The query I came up with is

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);`
Kunj
  • 77
  • 9

1 Answers1

0

You need to group by the users and count how many occurrences you have in usr_loc. If more than a single one, then replace the code by B. See below:

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;

Seems to me that you are using MySQL, rather than IBM DB2. Is that so?

The Impaler
  • 45,731
  • 9
  • 39
  • 76