简体   繁体   中英

how to select multiple columns with only one distinct column from joining two tables with all id's are UNIQUEIDENTIFIER using Nhibernate

Following is my table structure:

create table Department(
    deptid [UNIQUEIDENTIFIER] ROWGUIDCOL DEFAULT NEWSEQUENTIALID() NOT NULL CONSTRAINT Department_P_KEY PRIMARY KEY,
    departmentname varchar(100)
    )

create table Employee(
    empid [UNIQUEIDENTIFIER] ROWGUIDCOL DEFAULT NEWSEQUENTIALID() NOT NULL CONSTRAINT Employee_P_KEY PRIMARY KEY,
    name varchar(50), 
    city varchar(50),     
    deptid UNIQUEIDENTIFIER NOT NULL,
    foreign key(deptid) references Department(deptid) ON DELETE CASCADE ON UPDATE CASCADE
    )

My issue is that when I select mutliple columns and apply DISTINCT on one column with all primary keys and foreign keys are UNIQUEIDENTIFIER then that time query gives error message. my query and error as follows:

select distinct(Department.deptid),min(Employee.empid) as empid
from Employee
inner join Department on Department.deptid = Employee.deptid
group by Department.deptid

and Error message is :

Msg 8117, Level 16, State 1, Line 2 Operand data type uniqueidentifier is invalid for min operator.

But if Primary key and foreign key was int then above query will execute successfully because min function support to integer but how can I select distinct record using uniqueidentifier key.

And Following is my Nhibernate query:-

EmployeeEntity employeeEntity = new EmployeeEntity();
            employeeEntity.DepartmentMaster = new DepartmentEntity();
            ProjectionList projectionList = Projections.ProjectionList();
            projectionList.Add(Projections.Distinct(Projections.Property<EmployeeEntity>(x => x.DepartmentMaster)).WithAlias(() => employeeEntity.DepartmentMaster));
            projectionList.Add(Projections.Property<EmployeeEntity>(x => x.empid).WithAlias(() => employeeEntity.empid));

            IList<EmployeeEntity> query = null;
            query = NHSession.QueryOver<EmployeeEntity>()
            .Select(projectionList)
            .TransformUsing(Transformers.AliasToBean<EmployeeEntity>()).List<EmployeeEntity>();

How can I execute distinct query in sql first as per above sql query?.

Just convert the UniqueIdentifier to a string

select distinct(Department.deptid),min(CAST(Employee.empid AS NVARCHAR(36))) as empid
from Employee
inner join Department on Department.deptid = Employee.deptid
group by Department.deptid

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