我对SQL比较陌生,并希望学习一些简单的技巧。我设法创建了一个查询,选择每种不同类型的汽车许可证( chargeType ),计算为每个许可证发出的数量( num ),并添加一个列,显示签发的许可证总数(总计)。代码如下。
SELECT chargeType,
COUNT(chargeType) AS num,
(SELECT COUNT(chargeType)
FROM permit) AS total
FROM permit
GROUP BY chargeType
我现在想要添加一个最终列,显示每个发布的许可类型的百分比。所以每种许可类型的数量除以总数乘以100,但我很难做到。有人可以帮忙吗?
答案 0 :(得分:1)
尝试这样的事情
SELECT chargeType,
num,
total,
num / NULLIF(total, 0) * 100 AS Percenatge
FROM (SELECT chargeType,
Count(chargeType) AS num,
(SELECT Count(chargeType)
FROM permit) AS total
FROM permit
GROUP BY chargeType) a
NULLIF
用于避免除以零开始
答案 1 :(得分:0)
这会奏效。此解决方案的优点是SELECT
SELECT *, (num * 100 / total) as percentage
FROM
(
SELECT
chargeType,
COUNT(chargeType) AS num,
total,
(num * 100 / total) as percentage
FROM
(SELECT COUNT(chargeType) as total FROM permit) ttotal
CROSS JOIN
permit
GROUP BY
chargeType
) tsub