1,Group by 根据某个字段排序
select Department,count(*) FROM [PPMG].[dbo].[UnConViolation] group by Department
结果如下:
2,Group by与所传参数联合使用
USE PPMG SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO Alter PROCEDURE UnConViolationTimes @type nvarchar(50) AS BEGIN declare @sql nvarchar(1000) if @type is not null begin set @sql='select '+ @type+' as Name,count(*) as Count FROM [PPMG].[dbo].[UnConViolation] group by '+@type print @sql exec(@sql) end END GO
exec UnConViolationTimes 'Department'
结果如下
3,Group by 后台用法
public List<ViolationTimesDto> GetUnConViolationTimes(string type) { var UnConViolationList = UnConViolationRepository.Query(); var ttList = UnConViolationList.GroupBy(m => new { m.Department}).Select(m => new ViolationTimesDto() { Name=m.Key.Department, Count=m.Count() }).ToList(); return ttList; }
结果如下