简体   繁体   中英

SQL custom sort order for Exam Questions

For a project I am currently working on I need to create a list of questions that are sorted in a particular order and I'm currently not sure how to do that in SQL and I'm hoping someone might be able to help.

I have a list of questions and I want to be able to sort them by order of difficulty (Medium, Easy, Hard) but the twist is that if we have a list of 6 questions with 2 in each difficulty level then the order should look like

Medium,
Easy,
Hard,
Medium,
Easy,
Hard

If we have eight questions broken down into:

Easy x 3
Medium x 3
Hard x 2

They need to appear like:

Medium,
Easy,
Hard
Medium,
Easy,
Hard
Medium,
Easy

I'm starting to think that this is probably more likely the job of the PHP rather than SQL but if anyone has any advice I would appreciate it.

Edit: using MySQL/PHP

Thanks, Colin

This can be done using a row-number system. If you're using MSSQL you can use ROW_NUMBER , you mentioned using PHP so you're probably using MySQL, I'm not familiar with MySQL enough to give a solution for that platform.

First we PARTITION the data by difficulty and assign their own ROW_NUMBER, then we order by this generated row-number and then by difficulty, like so:

CREATE TABLE Questions (
    QuestionData ...,
    Difficulty nvarchar(10)
)

SELECT
    QuestionData,
    Difficulty,
    (
        CASE
            WHEN Difficulty = 'Medium' THEN 1
            WHEN Difficulty = 'Easy'   THEN 2
            ELSE                            3
        END
    ) AS DifficultyInt,
    ROW_NUMBER() OVER ( PARTITION BY Difficulty ORDER BY QuestionData ) AS RowNumber
FROM
    Questions
ORDER BY
    DifficultyInt

I made a SQLFiddle that uses Row_Number in SQl Server.

SELECT DIFFICULTY, ROW_NUMBER() OVER (PARTITION BY DIFFICULTY ORDER BY DIFFICULTY) AS RN
FROM TABLE1  
ORDER BY CASE DIFFICULTY WHEN 'MEDIUM' THEN 1 
                         WHEN 'EASY' THEN 2 
                         WHEN 'HARD' THEN 3 END, RN 

Thanks for the suggestions... From your answers for MSSQL I've been able to do a bit of research and come up with a solution for MySQL that I think should fit the bill.

SELECT    DIFFICULTY,
          @num := if(@type = DIFFICULTY, @num + 1, 1) as row_number,
          @type := DIFFICULTY as dummy
FROM      Table1 t
ORDER BY  row_number, CASE DIFFICULTY WHEN 'MEDIUM' THEN 1 
                         WHEN 'EASY' THEN 2 
                         WHEN 'HARD' THEN 3 END

See the SQL Fiddle example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM