[英]Group phone numbers that correspond at the same url in the same row
在數據庫中,有一些相等的行,其中僅更改電話號碼。 我想將對應於相同網址的單行電話號碼分組,以獲得第二張表。 我想知道是否有一種方法可以在mysql中通過一個或多個查詢或通過另一種方法來執行此操作。 提前致謝
Database1
Url |Company Name| Address | City |ZipCode|PHONE
www.aaa.com| AAA|StreetAAA|CityAAA| 00000|0000000000
www.aaa.com| AAA|StreetAAA|CityAAA| 00000|1111111111
www.aaa.com| AAA|StreetAAA|CityAAA| 00000|2222222222
www.bbb.com| BBB|StreetBBB|CityBBB| 11111|3333333333
www.ccc.com| CCC|StreetCCC|CityCCC| 22222|4444444444
www.ccc.com| CCC|StreetCCC|CityCCC| 22222|5555555555
www.ccc.com| CCC|StreetCCC|CityCCC| 22222|6666666666
www.ddd.com| DDD|StreetDDD|CityDDD| 33333|7777777777
www.ddd.com| DDD|StreetDDD|CityDDD| 33333|8888888888
www.eee.com| EEE|StreetEEE|CityEEE| 44444|9999999999
Final Database to generate:
Url |Company Name| Address | City |ZipCode| PHONE1 | PHONE2 | PHONE3
www.aaa.com| AAA|StreetAAA|CityAAA| 00000|0000000000|1111111111|2222222222
www.bbb.com| BBB|StreetBBB|CityBBB| 11111|3333333333| |
www.ccc.com| CCC|StreetCCC|CityCCC| 22222|4444444444|5555555555|6666666666
www.ddd.com| DDD|StreetDDD|CityDDD| 33333|7777777777|8888888888|
www.eee.com| EEE|StreetEEE|CityEEE| 44444|9999999999| |
最簡單的解決方案是將所有電話放入逗號分隔的列表中:
select url, companyname, address, city, zipcode,
group_concat(phone) as phones
from database1
group by url, companyname, address, city, zipcode;
但是,這並不是您想要的。 如果所有群組都有三個電話號碼,則以下內容更接近並可以使用:
select url, companyname, address, city, zipcode,
substring_index(group_concat(phone), ',', 1) as phone1,
substring_index(substring_index(group_concat(phone), ',', 2), ',', -1) as phone2,
substring_index(group_concat(phone), ',', -1) as phone3
from database1
group by url, companyname, address, city, zipcode;
因此,以下解決了此問題:
select url, companyname, address, city, zipcode,
(case when count(phone) >= 1
then substring_index(group_concat(phone), ',', 1)
end) as phone1,
(case when count(phone) >= 2
then substring_index(substring_index(group_concat(phone), ',', 2), ',', -1)
end) as phone2,
(case when count(phone) >= 3
then substring_index(group_concat(phone), ',', -1)
end) as phone3
from database1
group by url, companyname, address, city, zipcode;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.