1

I have a table named lists having below columns and rows.


   type     | time | alt_id       
------------+------+---------
 invest_fees| t1   |  5601
 invest_fees| t2   |  5601
 invest_fees| t3   |  5601
 countries  | t4   |  5601
 invest_fees| t5   |  5601
 invest_fees| t6   |  5601
 countries  | t7   |  5601
 countries  | t8   |  5601
 invest_fees| t9   |  5602
 countries  | t10  |  5602

I want to get this:

      type     | time | alt_id       
------------+------+---------
 invest_fees| t1   |  5601
 countries  | t4   |  5601
 invest_fees| t5   |  5601
 countries  | t7   |  5601
 invest_fees| t9   |  5602
 countries  | t10  |  5602

i.e. first occurrence of type every time it is found. Later, I want to find out the diff: t4-t1, t7-t5, t10-t9. Any ideas on how can I achieve this using sql? Thanks in advance.

forpas
  • 160,666
  • 10
  • 38
  • 76
sk17261205
  • 421
  • 1
  • 5
  • 12

1 Answers1

0

For MySQL 8.0+ you can use LAG():

SELECT t.type, t.time, t.alt_id
FROM (SELECT *, LAG(type) OVER() prev FROM tablename) t
WHERE t.prev IS NULL OR t.prev <> t.type

See the demo.
For previous versions use variables:

SET @rn := 0;
SET @type := null;
SELECT t.type, t.time, t.alt_id 
FROM (
  SELECT @rn := case 
    WHEN @type = type then @rn + 1 
    ELSE 1
  END AS rn, type, time, alt_id,
  @type := type  
  FROM tablename 
) t
WHERE t.rn = 1

See the demo.
Results:

| type        | time | alt_id |
| ----------- | ---- | ------ |
| invest_fees | t1   | 5601   |
| countries   | t4   | 5601   |
| invest_fees | t5   | 5601   |
| countries   | t7   | 5601   |
| invest_fees | t9   | 5602   |
| countries   | t10  | 5602   |
forpas
  • 160,666
  • 10
  • 38
  • 76