sqlserver group by後獲取其餘字段(多種方法)

你們都知道用group by的話,select 後面指定的字段必須與group by後面的一致。group by 只有個別字段,若是拿出其餘未分組的字段信息呢?在網上搜了下,sql

總結以下:函數

使用了group by 以後,就要求select後面的字段包含在group by 或聚合函數裏面,這時若是想讀取其它字段則沒法實現。sqlserver

將你須要的字段放進max或min函數中,max:支持字符類型、數字類型。
select
max(id) as id,username,password from users
group by username,password
order by id descserver

或者用:
select * from
(select part from employee group by part) as t1
inner join
(select distinct englishname from employee where part in (select part from employee group by part )) as t2
on t1.part =t2.partblog

參考:
select v.p ,v.a,v.b,v.c,v.d,v.e,v.f,v.g,v.h,v.i,v.j,v.k,v.l,v.m,v.m,v.n,v.o from vegaga v right join (
select min(id) as id,a,b,c,d,e,f,g,h,n from vegaga where a is not null group by a,b,c,d,e,f,g,h,n
) as v1 on v1.id=v.id order by v.id class

我在sqlserver中這樣寫,達到了我想要的效果。select

select max(CrmMemberID) as CrmMemberID,MemberName,COUNT("MemberName") as count_name
from [zfnewdb].[dbo].[tblCrmMemberAssign]
group by MemberName
having COUNT("MemberName") = 1im

不只拿到了MemberName字段,還拿到了我想要的CrmMemberID字段。想要其它字段繼續像上面的CrmMemberID字段那樣加上就好了。總結

相關文章
相關標籤/搜索