June 27, 2022 at 8:15 am
Just one more question. If I want for only to appear the fields 'MaxMinDesc' and the 'VacationHours' how would I do it? I have tried taking the asterixes off as below and it brings the fields 'MaxMinDesc' but not the 'VacationHours'
SELECT
CASE WHEN MaxRN =1 THEN 'Max' ELSE 'Min' END AS MaxMinDesc
FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY VacationHours DESC) AS MaxRN,
ROW_NUMBER() OVER (ORDER BY VacationHours ASC) AS MinRN
FROM HumanResources.Employee
) AS a
WHERE MaxRN = 1 OR MinRN = 1
June 27, 2022 at 1:08 pm
Just one more question. If I want for only to appear the fields 'MaxMinDesc' and the 'VacationHours' how would I do it? I have tried taking the asterixes off as below and it brings the fields 'MaxMinDesc' but not the 'VacationHours'
I don't know all the columns in the table so I retain the initial SELECT *, but the outer select needs only the MinMaxDesc and theVacationHours.
SELECT CASE WHEN a.MaxRN =1 THEN 'Max' ELSE 'Min' END AS MaxMinDesc,
a.VacationHours
FROM (
SELECT *
ROW_NUMBER() OVER (ORDER BY VacationHours DESC) AS MaxRN,
ROW_NUMBER() OVER (ORDER BY VacationHours ASC) AS MinRN
FROM HumanResources.Employee
) AS a
WHERE MaxRN = 1 OR MinRN = 1
I assumed you needed other columns like the Name or EmployeeID in the output which is why I suggested using row_number. If you only need the VacationHours then there are probably more efficient ways to do it. row_number is useful because it allows you to get a max or min and keep the entire row.
SELECT 'Min' AS MinMaxDesc,
MIN(VacationHours) AS VacationHours
FROM HumanResources.Employee
UNION ALL
SELECT 'Max',
MAX(VacationHours) AS VacationHours
FROM HumanResources.Employee
June 27, 2022 at 1:59 pm
That's great many thanks. Gosh wish I had similar level. Much appreciated for the thorough explanations.
Viewing 3 posts - 31 through 32 (of 32 total)
You must be logged in to reply to this topic. Login to reply