Tal Levi
Tal Levi

Reputation: 331

SQL Count by equal columns Query

I have this table:

subscriberID | date | segmentID | Counter
------------------------------------------
1            | 1.1  |    2      |    3 
1            | 2.1  |    4      |    2 
1            | 3.1  |    4      |    5 
2            | 1.1  |    1      |    12 
2            | 2.1  |    1      |    1
2            | 3.1  |    2      |    10 
3            | 1.1  |    2      |    4

I have to write SQL Query that does:

Get the top 3 most common segmentID's (by counter) for a given subscriberID.

can anyone help me with that? Thanks.

Upvotes: 0

Views: 24

Answers (1)

juergen d
juergen d

Reputation: 204854

select segmentID
from your_table
where subscriberID = 123
group by segmentID
order by sum(counter) desc

To get only 3 records you have to limit your result. Depending on your DB engine that could be top 3 or limit 3 or rownum <= 3.

Upvotes: 1

Related Questions