[英]How can I achieve the result I want using sql statement?
I have some data in my database. 我的数据库中有一些数据。 I tried to do a retrieval and it should appear in such a way.
我试图进行检索,它应该以这种方式出现。
Current table: 当前表:
FName| lName | phoneNo | year
Tom | Tan | 9123456 | 1
Tom | Tan | 9012345 | 1 <----extra row
What I want: 我想要的是:
FName | lName| phoneNo| year | phoneNo2
Tom | Tan | 9123456| 1 |9012345
How can I achieve this using sql statement? 如何使用sql语句实现此目的?
I would like to see if FName and lName are duplicated, then the duplicated data will be combined as such the phoneNo will be added into one column called phoneNo2. 我想看看FName和lName是否重复,那么重复的数据将被合并,因为这样的phoneNo将被添加到一个称为phoneNo2的列中。
Do a GROUP BY
, use MIN()
to get first phoneno and MAX()
to get the second. 执行
GROUP BY
,使用MIN()
获取第一个电话号码,并使用MAX()
获取第二个电话号码。
select FName, lName, min(phoneNo), max(year), max(phoneNo)
from tablename
group by FName, lName
You can also do a self LEFT JOIN
: 您也可以进行自我
LEFT JOIN
:
select t1.FName, t1.lName, t1.phoneNo, t1.year, t2.phoneNo
from tablename t1
left join tablename t2
on t1.FName = t2.FName and t1.lName = t2.lName
and t1.phoneNo < t2.phoneNo
Note: According to ANSI SQL YEAR
is a reserved word, so you may need to delimit it as "year"
. 注意:根据ANSI SQL,
YEAR
是保留字,因此您可能需要将其定为"year"
。
Another option which will cope with more than 2 phone numbers is to use GROUP_CONCAT 可以处理两个以上电话号码的另一个选项是使用GROUP_CONCAT
SELECT FName,
lName,
SUBSTRING_INDEX(GROUP_CONCAT(phoneNo), ',', 1) AS phoneNo,
`year`,
IF(COUNT(phoneNo) >= 2, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(phoneNo), ',', 2), ',', -1), NULL) AS phoneNo2,
IF(COUNT(phoneNo) >= 3, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(phoneNo), ',', 3), ',', -1), NULL) AS phoneNo3,
IF(COUNT(phoneNo) >= 4, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(phoneNo), ',', 4), ',', -1), NULL) AS phoneNo4,
IF(COUNT(phoneNo) >= 5, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(phoneNo), ',', 5), ',', -1), NULL) AS phoneNo5
FROM tablename
GROUP BY FName,
lName,
`year`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.