0

我是 MySQL 的新手,来自 Oracle 背景。我有一个 SQL 查询,用于计算表中类型的总数和百分比。

例如:

SELECT type,count(*) count_by_type ,a.tot total, (COUNT(*)*100/a.total) percent 
FROM xyz
JOIN (select count(*) tot from xyz)a
GROUP by type
HAVING type = 'abc';

此查询正在执行自联接。有没有更简单的方法来实现同样的目标?

4

2 回答 2

0

这里不需要使用SELF JOINHAVING子句。试试看:

SELECT COUNT(1) INTO @var_total FROM xyz;

SELECT type, count(1) AS count_by_type,
        @var_total total,
        (COUNT(1)*100/@var_total) AS percent
FROM xyz a
WHERE type = 'abc';
GROUP by type;
于 2012-07-31T04:30:28.143 回答
0
SELECT type,count(1) count_by_type ,(select count(1) from xyz) total,
(count_by_type*100/total) percent  FROM xyz WHERE type = 'abc'; 
于 2012-07-31T04:33:26.667 回答