2

I need help with creating sql query, I will present my problem in the picture

enter image description here

The photo above shows my prepared CTE table, what I want to achieve is table posted belove

enter image description here

Explanation
1. Column Group - If the value of the Type field is equal to T then we should set the next value starting from 1 to the next repetition of the value of T in the Type column
2. Column MaxGroupValueToPoint - Returns the largest value in the group it is in but we check from where the cursor is to the beginning of the group (sort by field id_ex asc)

CTE tabel contain 7+ million records

My problem is that I dont know how to achieve that group column.

1 Answer 1

1

It is doable with windowed functions:

WITH cte AS (
 SELECT *,grp=SUM(CASE WHEN [Type]='T'THEN 1 ELSE 0 END) OVER(PARITITON BY id ORDER BY id_ex)
 FROM tab
)
SELECT *, MaxGroupValueToPoint = MAX(Score) OVER(PARTITION BY id, grp ORDER BY id_ex)
FROM tab
ORDER BY id_ex;

How it works:

  • conditional SUM to create group, tick-tock mechanism, every 'T' adds 1

  • windowed MAX to grab highest value per group

1
  • "If you specify an ORDER BY but not a frame extent, the default is used, which is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW." Now i know why your query works.
    – Tomi
    Aug 25, 2019 at 10:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.