Skip to the content.

2. 去重

需求: 有一张学生成绩表(table_score),id, 学生id(s_id),学科id(p_id),分数(score)这么几个字段会出现同一个学生同一个学科有多个分数, 这时候的需求是 取表记录id较大的那个筛选出来

SELECT * FROM  table_score a
    WHERE NOT EXISTS
    (SELECT 1 FROM  table_score b
     WHERE a.s_id=b.s_id
           AND a.p_id=b.p_id
           AND a.id<b.id)

ps:此处有个坑,如果你查的表 table_score 含有条件,比如 我只需要查学生id在 200 ~ 500 之间的学生 这个条件不能加在上的语句中解决方法, 将此表添加条件后作为一张临时表 替换掉以上的 table_score .postgressql 可以 使用with语句, 其他DB可以考虑用类似的方式替代

WITH
    BASE_INFO AS
    (
        SELECT * FROM table_score WHERE s_id BETWEEN 200 AND 500
    )
SELECT
    *
FROM
    BASE_INFO a
WHERE
    NOT EXISTS
    (
        SELECT
            1
        FROM
            BASE_INFO b
        WHERE
            a.s_id=b.s_id
            --AND a.p_id=b.p_id
        AND a.id<b.id)

3. 删除表中重复的数据

select id from yalu_cost_price_monthly a
where a.id <>
(
   select max(b.id) from yalu_cost_price_monthly b
   where a.month = b.month and a.product_id = b.product_id  
);

只保留 数据中 month 和 product_id相同id最大的记录,其他都删除