MySQL 基础三 函数(聚合、字符串、时间、条件判断)
1.聚合
其它:GROUP_CONCAT、avg、sum、count、max、min
SELECT typeid,GROUP_CONCAT(goodsname) FROM `goods` GROUP BY typeid
2.日期函数
...
SELECT LENGTH('abc') SELECT CONCAT('a','b') -- ab SELECT CONCAT_WS(',','a','b') -- a,b SELECT *,CONCAT(NAME,sex),NAME+sex FROM student SELECT CONCAT('a',SPACE(5),'b') SELECT NOW() DECLARE @i DATETIME SET @i=NOW() SELECT @i; SELECT DAYOFYEAR(NOW()) SELECT SYSDATE() SELECT QUARTER('2017-01-01') SELECT DAY(NOW()) SELECT IF(1=1,2,3); SELECT IFNULL(1,2);
3.字符串函数
1)LOCATE,判断是否包含子字符串
2)SELECT SUBSTRING('abc11bbbb',1,1) 返回“a”
-- 创建函数 DELIMITER // CREATE FUNCTION fn_add(i INT,j INT) RETURNS INT BEGIN RETURN i+j; END // DELIMITER ; -- 创建函数 DELIMITER // CREATE FUNCTION fn_add2(i INT,j INT) RETURNS INT BEGIN -- 声明参数 DECLARE k INT; SET k=1; RETURN i+j+k; END // DELIMITER ; SELECT fn_add2(1,2) AS 'add';
4.字符串、日期转换
SELECT STR_TO_DATE('2018-02-1 11:23:34','%Y-%m-%d %H:%i:%S') SELECT DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%S')
5.转换函数
参考:https://www.cnblogs.com/conanwang/p/5917416.html
6.自定义函数
DELIMITER $$ USE `retailking`$$ DROP FUNCTION IF EXISTS `GetAllPriceByCaseNumId`$$ CREATE DEFINER=`root`@`%` FUNCTION `GetAllPriceByCaseNumId`(casenumid INT,registrationid VARCHAR(32)) RETURNS DECIMAL(8,2) BEGIN -- 获取病例的总金额 -- 撤单的,不能计算在内 DECLARE ActualMoney DECIMAL(8,2) DEFAULT 0; DECLARE price DECIMAL(8,2) ; SELECT IFNULL(SUM(hc.`ActualMoney`),0) INTO price FROM posregister hc WHERE hc.`Id`=registrationid AND hc.`PayState`!=4; -- 挂号 SET ActualMoney = ActualMoney + price; SELECT IFNULL(SUM(hc.`ActualMoney`),0) INTO price FROM hischeck hc WHERE hc.`CaseNumId`=casenumid AND hc.`PayState`!=4; -- 检查化验 SET ActualMoney = ActualMoney + price; SELECT IFNULL(SUM(hc.`ActualMoney`),0) INTO price FROM hisdispose hc WHERE hc.`CaseNumId`=casenumid AND hc.`PayState`!=4; -- 处置耗材 SET ActualMoney = ActualMoney + price; SELECT IFNULL(SUM(hc.`ActualMoney`),0) INTO price FROM `hisprescription` hc WHERE hc.`CaseNumId`=casenumid AND hc.`PayState`!=4; -- 处方 SET ActualMoney = ActualMoney + price; RETURN ActualMoney; END$$ DELIMITER ;
天生我材必有用,千金散尽还复来