我需要在sql中编写一段代码;del_ row";在列";调整名称"当存在重复的Id_number(例如:234566(,但恰好当Phone_number中的一个值以A开头而另一个以B开头时;del_ row";刚好在其中列"中的值为0的行中;电话号码"以";B";。想象一下,我有两个重复的id_number,其中一行的Phone_number以A开头,另一行以"A"开头;C";。在最后一种情况下,我什么都不想写。
Id_number | 电话号码 | 调整名称[/tr>|
---|---|---|
234566 | A5258528564 | |
675467 | A1147887422 | //tr>|
675534 | P1554515315 | |
234566 | B4141415882 | del_row |
234566 | C53465666655 | [/td>
一种方法
SELECT t.id_number, t.Phone_number,
CASE WHEN a.id_number IS NOT NULL THEN 'del_row' ELSE '' END as Adjustment_name
FROM mytable t
LEFT JOIN
(SELECT id_number from mytable
WHERE SUBSTRING(Phone_number FROM 1 FOR 1)='A') a
/* List of IDs that have a phone number starting with A */
ON a.id_number = t.id_number
AND SUBSTRING(t.Phone_number FROM 1 FOR 1)='B'
/* Only check for matching ID with A if this number starts with B */
一种相当粗糙的方法如下(假设您的手机排名为Axxx、Bxxx、Cxxx、Dxxx(。如果你的电话号码逻辑不同——这与你的req不太清楚——你可以相应地调整。
create table temp_table_1 as (
select id_number, phone_number
, case
when dense_rank() over(partition by id_number order by phone_number)>1
and phone_number like 'B%'
then 'del_row'
end adjustment_name
from your_table_name
) with data;
drop table your_table_name;
rename table temp_table_1 to your_table_name;