行的百分比

时间:2015-09-23 07:39:05

标签: mysql

让“总计”以下查询的结果:

SELECT COUNT(DISTINCT C1) from T where <something>

(“某事”是对T列的长期条件。)

让“partial1”结果:

SELECT COUNT(DISTINCT C1) from T where <something> AND C2>10.

和“partial2”结果:

SELECT COUNT(DISTINCT C1) from T where <something> AND C3>20.

有一种更好的方法来编写一个返回比率“partial1 / total”和“partial2 / total”的查询?如果total为零,则任何通常的默认值都可以是有效的(null,-1,1,100,...)。

1 个答案:

答案 0 :(得分:1)

如果您确实需要在MySql级别完成此操作,可以尝试以下方法:

SELECT
    partial1/total,
    partial2/total
FROM (
    SELECT 
        COUNT(DISTINCT C1) as total,
        COUNT(DISTINCT IF(C2>10, C1, NULL)) as partial1,
        COUNT(DISTINCT IF(C3>20, C1, NULL)) as partial2
    FROM T
    WHERE <something>
) as tmp
;