Вы можете написать функцию Split в MYSQL, проверьте эту ссылку
из ссылки
CREATE FUNCTION SPLIT_STR(
x VARCHAR(255),
delim VARCHAR(12),
pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
delim, '');
Использование
SELECT SPLIT_STR(string, delimiter, position)
Пример
SELECT SPLIT_STR('a|bb|ccc|dd', '|', 3) as third;
+-------+
| third |
+-------+
| ccc |
+-------+
Я не хочу красть гром Гордона здесь, потому что он сделал сложную роль.
Вот дополнительный бит , преобразующий NULL в «Первый раз».
create table #pivottabledata(Rownum int, PersonId int, Month int);
insert into #pivottabledata values(1,123,1);
insert into #pivottabledata values(2,123,2);
insert into #pivottabledata values(3,123,4);
insert into #pivottabledata values(4,123,5);
insert into #pivottabledata values(5,123,12);
insert into #pivottabledata values(1,222,1);
insert into #pivottabledata values(2,222,3);
insert into #pivottabledata values(3,222,4);
select * from #pivottabledata;
with cte (rownum,personid,month,diff) AS
(
select rownum, personid, month,
(month -
lag(month) over (partition by personid order by month)
) as diff
from #pivottabledata
)
SELECT rownum personid, month,
ISNULL(CAST(diff AS VARCHAR(max)), 'First Time') as diff
from cte;