仅当值之一具有NULL字段时,才在表中选择GROUP_BY和GROUP_CONCAT相同的值

时间:2018-09-06 19:49:13

标签: mysql sql group-concat

我有一张充满姓名和地址的表。我想合并(group_concat)具有相同的城市状态和名称值的所有行,但前提是地址之一是NULL值。例如,我可能有此表:

name     |    addr    |  city  | state  | phone 

jon snow | 123 got st |  la    | CA     | 1234567890
jon snow | NULL       |  la    | CA     | 1225556789
walker   | 777 diff ln|  la    | CA     | 4556678899
walker   |456 crown rd|  la    | CA     | 33344455566

我希望结果是:

name     |    addr    |  city  | state  | phone

jon snow | 123 got st |  la    | CA     | 1234567890,1225556789
walker   | 777 diff ln|  la    | CA     | 4556678899
walker   |456 crown rd|  la    | CA     | 33344455566

当前我正在使用以下命令:

SELECT name, group_concat(distinct(addr)) as addr, city, state, group_concat(distinct phone) as phone from got_table group by name, city, state having count(*) >1;

这最终将所有具有相同名称,城市和州的地址组合在一起,即使有两个非空地址也是如此。以上语句的结果如下:

name     |    addr                  |  city  | state  | phone

jon snow | 123 got st               |  la    | CA     | 1234567890,1225556789
walker   | 777 diff ln, 456 crown rd|  la    | CA     | 4556678899, 33344455566

有没有一种方法仅在行的地址之一为NULL时合并,并且仅在只有两行匹配时才执行此group_concat。

1 个答案:

答案 0 :(得分:2)

您可以尝试用子查询对CASE WHEN进行分组。

检查addr列是否NULL得到。

  1. addr为NULL可获得MAX值或按concat值的期望组。
  2. addr不为空,获取addr

看起来像这样。

CREATE TABLE got_table(
   name varchar(50),
   addr varchar(50),
  city varchar(50),
    state varchar(50),
    phone varchar(50)
); 


insert into got_table values ('jon snow','123 got st'  ,'la', 'CA', '1234567890');
insert into got_table values ('jon snow',NULL          ,'la', 'CA', '1225556789');
insert into got_table values ('walker','777 diff ln' ,'la', 'CA'  , '4556678899');
insert into got_table values ('walker','456 crown rd','la', 'CA'  , '33344455566');

查询1

SELECT name,
       case when addr is null then
       (
         SELECT MAX(tt.addr) 
         FROM got_table tt
         WHERE t1.name = tt.name 
         and t1.city = tt.city 
         and t1.state = tt.state
       ) else addr end as address,
       city, 
       state, 
       group_concat(distinct phone) as phone 
from got_table t1
group by name, city, state,address

Results

|     name |      address | city | state |                 phone |
|----------|--------------|------|-------|-----------------------|
| jon snow |   123 got st |   la |    CA | 1225556789,1234567890 |
|   walker | 456 crown rd |   la |    CA |           33344455566 |
|   walker |  777 diff ln |   la |    CA |            4556678899 |