SQL Server mode SQL

后端 未结 3 1354
我在风中等你
我在风中等你 2021-01-21 16:49

I have a table that list students\' grades per class. I want a result set that looks like:

BIO...B
CHEM...C

Where the \"B\" and \"C\" are the m

相关标签:
3条回答
  • 2021-01-21 17:06

    Use a GROUP BY clause.

    SELECT className, ClassMode(className)
    FROM Grades
    GROUP BY className
    

    Your Mode() function would have to be created of course, but it would be a simple function like:

    CREATE FUNCTION ClassMode(@ClassName varchar(50))
    RETURNS varchar(2)
    AS
    BEGIN
        Declare @temp varchar(2)
    
        SELECT @temp = TOP 1 Grade, COUNT(*) Grades as frequency
        FROM Grades
        WHERE ClassName = @ClassName
        GROUP BY ClassName
        ORDER BY frequency DESC
    
        RETURN @temp
    END
    
    0 讨论(0)
  • 2021-01-21 17:09

    You just need to GROUP BY ClassName

    SELECT ClassName, MODE(Grade) FROM YourTable GROUP BY ClassName
    
    0 讨论(0)
  • 2021-01-21 17:11

    here, something like this on SQL 2005/2008:

    ;WITH 
      Counts AS (
        SELECT ClassName, Grade, COUNT(*) AS GradeFreq 
        FROM Scores
        GROUP BY ClassName, Grade
        )
    , Ranked AS (
        SELECT ClassName, Grade, GradeFreq
        , Ranking = DENSE_RANK() OVER (PARTITION BY ClassName ORDER BY GradeFreq DESC)
        FROM Counts
        )
    SELECT * FROM Ranked WHERE Ranking = 1
    

    or perhaps just:

    ;WITH Ranked AS (
      SELECT 
        ClassName, Grade
      , GradeFreq = COUNT(*)
      , Ranking = DENSE_RANK() OVER (PARTITION BY ClassName ORDER BY COUNT(*) DESC)
      FROM Scores
      GROUP BY ClassName, Grade
      )
    SELECT * FROM Ranked WHERE Ranking = 1
    
    0 讨论(0)
提交回复
热议问题