Question

I've been trying to find a way to use the row_number over partition by, but couldn't find how to do so in SQLite. I'm trying to convert the following the working query from MSSQL syntax to SQLite:

    select TKG, hour, CAP, switch, Calls
from 
(
  select *,
    row_number() over(partition by TKG order by cap desc) rn
  from yourtable 
) t1
where rn = 1

Here's an example with SQLFiddle: http://sqlfiddle.com/#!3/7bf9a/3

Basically, I have the following table:

TKG   hour  CAP SWITCH  CALLS
AAA   7     45  HH      56
AAA   8     35  HH      76
AAA   9     25  HH      43
BBB   7     32  LL      5
BBB   8     43  LL      65
BBB   9     434 LL      65
CCC   7     54  JJ      43
CCC   8     564 JJ      43
CCC   9     54  JJ      65
ddd   7     10  MM      4
ddd   8     10  MM      3
ddd   9     10  MM      5

I need to order by the TKG with the max CAP so the output will look like this:

TKG hour    CAP SWITCH  CALLS
AAA 7       45  HH      56
BBB 9       434 LL      65
CCC 8       564 JJ      43
ddd 7       10  MM      4
Was it helpful?

Solution

Without knowing unique key it's really hard to do in readable way (no cross apply, no windowed functions). If you can afford to add id into your table, you can do:

select *
from yourtable
where
    id in (
        select min(y.id)
        from yourtable as y
            inner join (
            select [TKG], max([CAP]) as [CAP]
            from yourtable
            group by [TKG]
        ) as y2 on y2.[TKG] = y.[TKG] and y2.[CAP] = y.[CAP]
        group by y.[TKG]
    )

sql fiddle demo

Considering myself lucky that I don't work in SQLite often :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top