• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

find MODE (with groupings) in T-SQL

Homerboy

Lifer
I'm trying to find the MODE for a set of data.
However I need it group by a specific column -- meaning I want to run my query and have multiple rows returned showing the MODE of the data in question for each row.

The query is this:

Code:
select
TOP 1
master.VENUE1_NO,
COUNT(*) as 'frequency',

field

from master inner join INFINITY on master.FILENO = infinity.FILENO
where CODE = '*lgldt'
and master.FORW_NO IN (2256, 2356, 2357, 2358, 2359)
and FIELD <= GETDATE()
--and DATEDIFF(MONTH,FIELD,GETDATE()) <= 4
and field is not null
group by master.VENUE1_NO, FIELD
order by COUNT(*) DESC

What that will currently give me is ONE row of data.
What I want is a row for EACH master.VENUE1_NO and the MODE per master.VENUE1_NO

I just can not wrap my brain around this.

***WARNING***
once I get this, I will need to tackle the same thing for MEDIAN.


Thanks in advance.
 
I did some more google digging.
I guess what I really want to do here is "Top n Per Group"
But, admittedly, I'm having issues wrapping my head around it still.
 
I'm trying to find the MODE for a set of data.
However I need it group by a specific column -- meaning I want to run my query and have multiple rows returned showing the MODE of the data in question for each row.

The query is this:

Code:
select
TOP 1
master.VENUE1_NO,
COUNT(*) as 'frequency',

field

from master inner join INFINITY on master.FILENO = infinity.FILENO
where CODE = '*lgldt'
and master.FORW_NO IN (2256, 2356, 2357, 2358, 2359)
and FIELD <= GETDATE()
--and DATEDIFF(MONTH,FIELD,GETDATE()) <= 4
and field is not null
group by master.VENUE1_NO, FIELD
order by COUNT(*) DESC

What that will currently give me is ONE row of data.
What I want is a row for EACH master.VENUE1_NO and the MODE per master.VENUE1_NO

I just can not wrap my brain around this.

***WARNING***
once I get this, I will need to tackle the same thing for MEDIAN.


Thanks in advance.

You'd have to do sub query to first group by the field, then an outer query to join and order.

Code:
SELECT TOP N a.field, b.* FROM a INNER JOIN (SELECT primary_key, COUNT(*)
 AS count FROM b GROUP BY primary_key) AS b ON a.primary_key=b.primary_key 
ORDER BY b.count DESC
 
Use the RANK() function inside a CTE and select what you are looking from there. You can use multiple RANK() functions in a statement with various groupings.
 
Back
Top