Select first record within a segmentation in SQL Server

10

I have the following example table:

The query asks me to show which students entered first in each course. I can tell which student entered the university first, using the top(1) function, but how can I do this for each course?

    
asked by anonymous 29.08.2017 / 16:48

3 answers

9

Use the ROW NUMBER function, it will display a sort of "break" in case, per course code.

    SELECT * 
        FROM 
        (SELECT ROW_NUMBER () OVER (PARTITION BY codigo_curso ORDER BY data_ingresso ) as ROW_NUM
, *
         FROM NOME_TABELA
        ) TB_AUX
    WHERE ROW_NUM = 1 
    
29.08.2017 / 17:05
10

CTE with ROW_NUMBER()

;WITH CTE AS
(
   SELECT *,
         ROW_NUMBER() OVER (PARTITION BY codigo_curso ORDER BY data_ingresso) AS row
   FROM ALUNOS
)
SELECT *
FROM CTE 
WHERE row= 1

SubQuery Correlated:

SELECT l.*
FROM
  (SELECT ALUNOS.*,
           ROW_NUMBER() OVER (PARTITION BY codigo_curso
                              ORDER BY data_ingresso) AS linha
   FROM ALUNOS) l
WHERE l.linha = 1;

SQLFiddle

Update

Today I learned a different way of doing a query that will generate the same result.

SELECT * 
FROM ALUNOS
INNER JOIN(SELECT codigo_curso, MIN(data_ingresso) data_ingresso
    FROM ALUNOS
    GROUP BY codigo_curso) A
ON ALUNOS.codigo_curso = A.codigo_curso
AND ALUNOS.data_ingresso = A.data_ingresso
  • Get the smallest data_ingresso grouped by codigo_curso
  • Make a JOIN with this result.

You meant to SQL:

  

Return students who have joined a particular course first.

  • PARTITION BY value_expression - value_expression specifies the column by which the result set is partitioned.
  • Order_by_clause - Determines which orders the rows will be assigned to.

Row Number in a nutshell will assign an order to your lines.

Recommended Readings:

29.08.2017 / 17:07
7

Interesting question. I went to search and found this answer :

;WITH cte AS
(
   SELECT *,
         ROW_NUMBER() OVER (PARTITION BY codigo_curso ORDER BY data_ingresso DESC) AS rn
   FROM tusu
)
SELECT *
FROM cte
WHERE rn = 1

I've only used it for testing, but it seems to work for what you need.

    
29.08.2017 / 17:07