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?
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
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;
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
data_ingresso
grouped by codigo_curso
JOIN
with this result. You meant to SQL:
Return students who have joined a particular course first.
value_expression
specifies the column by which the result set is partitioned. Row Number
in a nutshell will assign an order to your lines.
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.