MySQL组合多个计数查询

时间:2011-09-06 15:36:28

标签: mysql count

我有以下查询:

SELECT COUNT(package) as advanced_count FROM users WHERE package = '2' AND site_url is     NOT NULL;

我想要做的是再获得2个查询以获取basic_count,然后再获得基本+高级的total_count。

我的另一个基本查询是:

SELECT count(package) as basic_count FROM users WHERE package = '1' AND site_url is NOT NULL

但是我不确定如何将两者结合起来,所以它只是一个查询,然后再添加总数。

我希望有人能指出我正确的方向。

谢谢!

1 个答案:

答案 0 :(得分:4)

SELECT SUM(CASE WHEN package = '2' THEN 1 ELSE 0 END) AS advanced_count,
       SUM(CASE WHEN package = '1' THEN 1 ELSE 0 END) AS basic_count,
       COUNT(*) AS total_count
    FROM users
    WHERE site_url IS NOT NULL
        AND package IN ('1', '2');