2

I have a table as this example:

CREATE TABLE customerEvent(
    customerID  int NOT NULL,
    eventID     int NOT NULL
)

customerID may appear in many records. I use the following query to identify most frequent customerID:

SELECT
    customerID,eventID
    ,row_number() OVER(PARTITION BY customerID ORDER BY eventID) as frequency
FROM customerEvent
ORDER BY frequency DESC

With this I see those most frequent customerID. But they appear only once on the top of the list. Example:

customerID  eventID frequency
7           3       5
15          9       4
7           1       4
9           4       3
7           10      3
15          2       3

I need all records of the most frequent customerID to appear on the top, example:

customerID  eventID frequency
7           3       5
7           1       4
7           10      3
15          9       4
15          2       3
9           4       3

Any idea how I can build a query that does that?

1
  • The second order isn't relevant. It may be eventID, or any other field on the table. What's important is that all records of the most frequent customerID to come first, then all records of the second most frequent customerID, then all of the third, etc.
    – Hikari
    Commented Aug 14, 2015 at 14:11

1 Answer 1

7

It seems you don't really need the "frequency" for the sorting, only the "maximum frequency" per customer. You can use the COUNT(*) OVER (PARTITION BY customerID):

SELECT
    customerID, 
    eventID,
    ROW_NUMBER() OVER (PARTITION BY customerID ORDER BY eventID) AS frequency  
FROM 
    customerEvent
ORDER BY 
    COUNT(*) OVER (PARTITION BY customerID) DESC,
    customerID,
    frequency DESC ; 

The second part of the order by needs to be customerID just in case of ties. I assume that if you have two or more customers with the same number of events, you don't want their events mixed up.

2
  • lol it worked tnx! In fact I replaced row_number() for count() whatsoever. I don't need to count records at all, I need the amount of incidences of each customerID.
    – Hikari
    Commented Aug 14, 2015 at 14:23
  • yes, you could do that. if you don't want that number (say 5 events for customer A) in the output, you can even remove the count() from the SELECT list and keep it only in the ORDER BY list. Commented Aug 14, 2015 at 14:25

Your Answer

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

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