先说一下需求:
本来是用Excel表操作的,但每次都需要把数据全都循环遍历读取出来才能做下一步处理,效率很低.
索性导入数据库里搞一搞…也是个挺恶心的需求
数据库表结构:
不要吐槽我的命名全是拼音首字母哈,临时验证的一个小功能,图个省时省力而已.
DROP TABLE IF EXISTS `jiage`; CREATE TABLE `jiage` ( `xl` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '小类', `ppzj` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '匹配总价', `xqpc` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '需求批次', `xqbh` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '需求编号', `xqrq` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '需求日期', `ppsl` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '匹配数量', `ppdj` float(10, 2) DEFAULT NULL COMMENT '匹配单价', `wlms` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '物料描述', `lxr` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '联系人', `ywlx` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '业务类型', `wlbm` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '物料编码' ) ENGINE = MyISAM CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '物料数据校对表' ROW_FORMAT = Dynamic;
要做的就是根据 物料编码
分组查询出每组中 匹配单价
最高的一条记录.
好了开始写数据库语句了:
我使用的是下面这种方式
方式1:内层使用DISTINCT
SELECT xl, ppdj, wlms, wlbm FROM ( SELECT DISTINCT XL AS xl, PPDJ AS ppdj, WLMS AS wlms, WLBM AS wlbm FROM `jiage` ORDER BY ppdj DESC ) f GROUP BY wlbm;
还有一种方式2,是用limit查询的,跟我的需求不太匹配就没试,贴出来备用
select id,user_name,user_sex,user_age from ( SELECT id,user_name,user_sex,user_age FROM `user_test` order by user_age limit 100 )A group by A.user_sex