[英]SQL : Select Distinct rows by all columns but omit one column (say ID column)
[英]how to select multiple columns with only one distinct column from joining two tables with all id's are UNIQUEIDENTIFIER using Nhibernate
以下是我的表結構:
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
)
我的問題是,當我選擇多個列並在所有主鍵和外鍵都為UNIQUEIDENTIFIER
一列上應用DISTINCT
,該時間查詢會給出錯誤消息。 我的查詢和錯誤如下:
select distinct(Department.deptid),min(Employee.empid) as empid
from Employee
inner join Department on Department.deptid = Employee.deptid
group by Department.deptid
錯誤消息是:
消息8117,級別16,狀態1,行2操作數數據類型uniqueidentifier對min運算符無效。
但是,如果主鍵和外鍵為int,則上述查詢將成功執行,因為min函數支持整數,但是如何使用uniqueidentifier鍵選擇不同的記錄。
以下是我的Nhibernate查詢:-
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>();
如何按照上述sql查詢先在sql中執行不同的查詢?
只需將UniqueIdentifier轉換為字符串
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.