I have a table with something like this.
abc-cde-0001222
abc-cde-0001223
abc-ced-0001224
cde-efg-0003001
ced-efg-0003002
ced-efg-0003008
I wish to select abc-cde-0001222, abc-ced-0001224
also cde-efg-0003001 , cde-efg-0003002
ced-efg-0003008 , ""
See, I need to obtain 1st and last values of a range. If the particular value is only one item (not in a range) I want it to select as the 1st value and a null value.
So far I have only a Idea of using IF
and increment operator
(If this is possible). I can do the formatting and obtain the Int value using
SELECT field, CONVERT(SUBSTRING_INDEX(field,'-',-1), UNSIGNED INTEGER) AS num
FROM table
ORDER BY num;
Please could you give me a hand... Lot appreciated
This is a pain in MySQL. But, it is possible. The logic is to find where a sequence starts. You can do this with a correlated subquery and some arithmetic. Then you want a cumulative sum of the starts. This is harder, because it requires doing a correlated subquery on the correlated subquery.
First, to set the NullIfStart
variable:
select t.*,
(select 0
from t t2
where left(t2.field, 8) = left(t.field, 8) and
t2.field < t.field and
right(t2.field, 7) + 0 = right(t.field, 7) + 0 - 1
) as NullIfStart
from t;
This gets the cumulative sum, which can be used as a grouping field:
select t.*
(select sum(NullIfStart is null)
from (select t1.*,
(select 0
from t t2
where left(t2.field, 8) = left(t1.field, 8) and
t2.field < t1.field and
right(t2.field, 7) + 0 = right(t1.field, 7) + 0 - 1
) as NullIfStart
from t t1
) tnis
where right(tnis.field, 7) = right(t.field, 7) and
tnis.field <= t.field
) grp
from t;
The final solution is to do the aggregation:
select min(field),
(case when max(field <> min(field) then max(field) end)
from (select t.*
(select sum(NullIfStart is null)
from (select t1.*,
(select 0
from t t2
where left(t2.field, 8) = left(t1.field, 8) and
t2.field < t1.field and
right(t2.field, 7) + 0 = right(t1.field, 7) + 0 - 1
) as NullIfStart
from t t1
) tnis
where left(tnis.field, 8) = left(t.field, 8) and
tnis.field <= t.field
) grp
from t
) s
group by left(s.field, 8), grp;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.