SQL有哪些常用的聚合函数?如何使用?

入门SQL

答题要点

-- COUNT:计数
SELECT COUNT(*) FROM users;                    -- 总行数
SELECT COUNT(phone) FROM users;                -- 非NULL的phone数量
SELECT COUNT(DISTINCT city) FROM users;        -- 不同城市数量

-- SUM:求和
SELECT SUM(amount) FROM orders;

-- AVG:平均值
SELECT AVG(amount) FROM orders;

-- MAX/MIN:最大/最小值
SELECT MAX(amount), MIN(amount) FROM orders;
SELECT MAX(created_at) FROM users;             -- 最新日期

-- 组合使用
SELECT
    COUNT(*) as total_orders,
    SUM(amount) as total_amount,
    AVG(amount) as avg_amount,
    MAX(amount) as max_amount,
    MIN(amount) as min_amount
FROM orders
WHERE status = 'completed';

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题