Skip to content
Advertisement

Query based on some data multiple compare

Table:

enter image description here

How do i bring the period when customers have max cc_limit? If the cc_limits same for customer for more than one month, take the period with highest year-month data

Advertisement

Answer

Use row_number() window function,Below should work.

EDIT : To clarify why order by should be in the inline view.

Scenario : When there are duplicate records for same cc_limit and cust_no,the requirement is to retrieve highest yearmonth record.

The default order of data retrieval for any table is by the order they are inserted unless a filter caused an index to be used to filter data.

Suppose 201912 record is inserted first followed by 201911(Not possible practically though, may be during a database reorganization the order of insertion got flipped) then without order by clause would return 201911 record instead of 201912.

# cust_no 1 has 201912 record inserted first and then 201912 and has same cc_limit.

When the query is executed without order by in the inline view,

The yearmonth returned for cust_no 1 is 201911 instead of 201912

enter image description here

But the query with order by clause would ensure that latest yearmonth record being returned,

enter image description here

I have demonstrated the whole behaviour in DBFIDDLE link for MySQL8.0 – https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=03b06094d10a0daf7732f0cb19798262

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement