The below query is a simple select, but i need to select Nationality as distinct, while also selecting type and category (both not distinct). Any way to do so?
SELECT NATIONALITY,TYPE,CATEGORIE FROM EMPLOYEE
The below query is a simple select, but i need to select Nationality as distinct, while also selecting type and category (both not distinct). Any way to do so?
SELECT NATIONALITY,TYPE,CATEGORIE FROM EMPLOYEE
Try:
SELECT NATIONALITY,TYPE,CATEGORIE FROM EMPLOYEE
Group by NATIONALITY,TYPE,CATEGORIE
I'm assuming that you have same type and category for same nationality. In the other possibility where you can have different categories and types for the same nationality:
You have different records for each nationality, and you want to select one for each, but what should be the value of TYPE and CATEGORY? you need to chose one using an aggregate function (Max, Min, Avg...)
Ex:
SELECT NATIONALITY,max(TYPE),max(CATEGORIE) FROM EMPLOYEE
Group by NATIONALITY
Assuming the structure of EMPLOYEE table is similar to below-
NATIONALITY TYPE CATEGORY
American A NR
American C SR
American C SR
American B GEN
Indian A SR
Indian A NR
Indian B NR
Indian B NR
Indian B GEN
Italian C GEN
Italian A SR
Italian B SR
And the requirement is to fetch one record for each NATIONALITY with any combination of TYPE and CATEGORY available for that NATIONALITY.
To do so, you can first partition the table on NATIONALITY and add row_number (). The Partition function maps the rows of a table into partitions based on the values of a specified column. Using row_number() on that, will add row numbers from 1 to N for each NATIONALITY. Then later this can be used with a where clause for row_number() = 1.
SELECT *, row_number() over(partition by NATIONALITY order by Nationality)
as RowNum from EMPLOYEE
The result will be as follows:
NATIONALITY TYPE CATEGORY RowNum
American A NR 1
American C SR 2
American C SR 3
American B GEN 4
Indian A SR 1
Indian A NR 2
Indian B NR 3
Indian B NR 4
Indian B GEN 5
Italian C GEN 1
Italian A SR 2
Italian B SR 3
Now the above table can be used under Common Table Expression (CTE) and can be easily queried for RowNum = 1. CTE can be thought of as a temporary result set that is defined within the execution scope of a single SELECT. It is not stored as an object and lasts only for the duration of the query.
WITH MyCte AS
(
SELECT *,row_number() over(partition by NATIONALITY order by Nationality)
as RowNum
from EMPLOYEE
)
SELECT NATIONALITY, [TYPE], CATEGORY
FROM MyCte
WHERE RowNum =1
The result will be as follows:
NATIONALITY TYPE CATEGORY
American A NR
Indian A SR
Italian C GEN