Home Forums SQL Server 2008 T-SQL (SS2K8) Comparing row counts and displaying results from greatest row count from a single table RE: Comparing row counts and displaying results from greatest row count from a single table

  • ;WITH SampleData AS (

    SELECT * FROM (values

    ('8009874321', 'cars'),

    ('8009874321', 'Newsales'),

    ('8009874321', 'Newsales'),

    ('8009870000', 'Newsales'),

    ('8009870000', 'BenaSales'),

    ('8009870000', 'BenaSales'),

    ('8009870000', 'BenaSales2'),

    ('8009870000', 'BenaSales2')

    ) sampleData ([800num], CompanyName))

    SELECT [800num], CompanyName

    FROM (

    SELECT [800num], CompanyName,

    dr = DENSE_RANK() OVER(PARTITION BY [800num] ORDER BY cnt DESC)

    FROM (

    SELECT [800num], CompanyName, cnt = COUNT(*)

    FROM SampleData

    GROUP BY [800num], CompanyName

    ) d

    ) e

    WHERE dr = 1

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden