SQLite Forum

Select distinct from most recent record
Login
Easiest is to do:

```
SELECT col1, col2, typeof(col2) FROM t;
```

Assuming that what Keith suggested IS the case, this query should fix you right up:


```
SELECT col1, MAX(CAST(col2 AS INT))
  FROM t
 GROUP BY col1
;
```

Or this using a CTE or sub-query to first get the real (fixed) table values then grouping it:

```
-- WITH CTE:
WITH tReal(c1,c2) AS (
    SELECT col1, CAST(col2 AS INT)
    FROM t
)
SELECT c1, MAX(c2) AS Latest
  FROM tReal
;


-- Sub-Query:
SELECT S.c1, MAX(S.c2) AS Latest
  FROM (
    SELECT col1 AS c1, CAST(col2 AS INTEGER) AS c2 FROM t
  ) AS S
;
```

Note that these may produce errors or weird results if the columns do contain actual alpha characters and not just valid integer numeric values.

Note also that technically SQLite does not require aliasing the sub-query (the "AS S" bit), but many other SQL engines do, so I used that in the example.


You could also permanently "fix" the table, if the above assumption is what is going on and the above queries work, then this should work:

```
UPDATE t SET col2 = CAST(col2 AS INT) WHERE 1;
```

Backup your data before doing any such thing.