本文主要记录日常开发中经常用到的SQL函数,便于复查自用。
TRUNC(MONTHS_BETWEEN(SYSDATE, '出生日期') / 12)
-- 包含1965-01-01,不含1990-01-01
TO_DATE(TRUNC(DBMS_RANDOM.VALUE(TO_CHAR(TO_DATE('1965-01-01', 'yyyy-MM-dd'), 'J'), TO_CHAR(TO_DATE('1990-01-01', 'yyyy-MM-dd'), 'J'))), 'J')
-- 包含x,不含y(左闭右开)
TRUNC(DBMS_RANDOM.VALUE(x, y))
BEGIN
-- for循环遍历表中每一行数据,i为游标变量,用于引用每一行的值
FOR i IN (SELECT * FROM table_name) LOOP
UPDATE table_name
SET column_name = (
SELECT
listagg(str, '、') WITHIN GROUP (ORDER BY dbms_random.random)
FROM (
SELECT 'A' AS str FROM DUAL UNION ALL
SELECT 'B' AS str FROM DUAL UNION ALL
SELECT 'C' AS str FROM DUAL
)
WHERE rownum <= dbms_random.value(1, 4)
)
WHERE ID = i.ID;
END LOOP;
END;
BEGIN
FOR i IN (SELECT * FROM PHS169_JK_TUMORINFO WHERE (MONTHS_BETWEEN(SYSDATE, TO_DATE(SUBSTR(VC_SFZH, 7, 8), 'YYYYMMDD')) / 12) <= 35) LOOP
UPDATE PHS169_JK_TUMORINFO
SET VC_SFZH = (
SUBSTR(VC_SFZH, 1, 6)
|| TO_CHAR(TO_DATE(TRUNC(DBMS_RANDOM.VALUE(TO_CHAR(TO_DATE('19630101', 'YYYYMMDD'), 'J'), TO_CHAR(TO_DATE('19831231', 'YYYYMMDD'), 'J'))), 'J'), 'YYYYMMDD')
|| SUBSTR(VC_SFZH, 15)
)
WHERE i.VC_ID = VC_ID;
END LOOP;
END;
TIMESTAMPDIFF(YEAR, '出生日期', CURDATE())
-- 根据列1分组后使用指定分隔符聚合展示列2(支持去重,不指定分隔符则为默认的",")
SELECT '列1', GROUP_CONCAT([DISTINCT] '列2' [SEPARATOR '指定分隔符']) FROM '表名' GROUP BY '列1'
参考文章:传送门
FIND_IN_SET(str,strlist)
-- 返回str在strlist中的位置(不存在则返回0)
-- 常用于WHERE语句后作为条件来辅助查询
SELECT FIND_IN_SET('b', 'a,b,c');
-- 结果:2
SELECT FIND_IN_SET('d', 'a,b,c');
-- 结果:0
DELETE FROM deduct_table WHERE id in (
-- 此处必须多嵌套一层,否则会报错
SELECT t.id FROM (
SELECT d.id
FROM deduct_table d
WHERE
(d.order_id, d.deduct_date) in (
SELECT order_id, deduct_date
FROM deduct_table
GROUP BY order_id, deduct_date
HAVING
COUNT(*) > 1
-- 删除当天首次扣款以外的所有重复扣款
AND _rowid NOT IN (SELECT MIN(_rowid) FROM deduct_table d1 GROUP BY d1.order_id, d1.deduct_date HAVING COUNT(*) > 1)
)
) t
)