Sql Server 中在group by分组后,同时查询表中其它在select中的列,但不希望进行分组的数据
最近帮朋友处理一批数据,将指定的列重复的数据拿出来。这些数据在excel里。有10W条左右。由于EXCEL不好操作。就想着将数据导入数据库通过SQL语句来操作。
导入数据库成功了,但由于SQL不是很牛,所以查询有些问题。
我用group by 把重复的拿掉,但还有个问题,大家都知道用group by的话,select 后面指定的字段必须与group by后面的一致。group by 只有个别字段,如果拿出其他未分组的字段信息呢?在网上搜了下,
总结如下:
使用了group by 之后,就要求select后面的字段包含在group by 或聚合函数里面,这时如果想读取其它字段则无法实现。
将你需要的字段放进max或min函数中,max:支持字符类型、数字类型。
案例介绍
select max(id) as id,username,password from users group by username,password order by id desc
declare @JWorkDatestart DATETIME, @JWorkDateend DATETIME SET @JWorkDatestart ='{0}' SET @JWorkDateend = '{1}' SELECT JWorkDate AS 工作日期, dbo.JL_ProductionCenter.Name AS 生产中心, dbo.JL_P_B_Equipment.Name AS 设备, dbo.jzClassID.NAME AS 班次, CASE WHEN MIN(JType) = 1 THEN MIN(jzSysUser.name) ELSE null END AS 接班人员, CASE WHEN MIN(JType) = 1 THEN MIN(JDate) ELSE null END AS 接班时间, CASE WHEN MAX(JType) = 2 THEN MAX(jzSysUser.name) ELSE null END AS 交班人员, CASE WHEN MAX(JType) = 2 THEN MAX(JDate) ELSE null END AS 交班时间 FROM dbo.JL_DisklessWorkstation_Attendance LEFT JOIN dbo.JL_P_B_Equipment ON dbo.JL_P_B_Equipment.ID = dbo.JL_DisklessWorkstation_Attendance.JEquipmentID LEFT JOIN dbo.JL_ProductionCenter ON dbo.JL_ProductionCenter.ID = dbo.JL_P_B_Equipment.JProductionCenterID LEFT JOIN dbo.jzClassID ON dbo.jzClassID.ID = dbo.JL_DisklessWorkstation_Attendance.JClassID LEFT JOIN dbo.jzSysUser ON dbo.jzSysUser.ID = dbo.JL_DisklessWorkstation_Attendance.JUserID WHERE datediff(day,JWorkDate,@JWorkDateend)>=0 AND datediff(day,@JWorkDatestart,JWorkDate)>=0 GROUP BY JWorkDate,dbo.JL_ProductionCenter.Name,dbo.JL_P_B_Equipment.Name,dbo.jzClassID.NAME ORDER BY JWorkDate DESC
L-Rui