选择列的百分比
Posted
技术标签:
【中文标题】选择列的百分比【英文标题】:Selecting the percentage of a column 【发布时间】:2020-11-23 10:32:23 【问题描述】:我想要做的是选择满足特定条件的列的特定百分比。我已经在这个网站上搜索了它并找到了答案,但是我自己使用它时它不起作用。我想知道我做错了什么
SELECT Total FROM(
SELECT Collected FROM (
SELECT COUNT(status) FROM Requests AS Collected
WHERE status = "A") / COUNT(status))
FROM Requests
正如您在此处看到的,我想要状态为“A”的百分比。谁能告诉我这里出了什么问题?
编辑:感谢您提出问题的反馈。我有的是表requests
。我想知道状态为“A”的百分比。
请求表示例数据:
+--------+--------+ |号码 |状态 | +--------+--------+ | 1 |一个 | | 2 |乙| | 3 |乙| | 4 |一个 | | 5 |乙| +--------+--------+想要的结果:
+-----------------+ | Percentage_Of_A | +-----------------+ | 40.0 | +-----------------+错误:`您的 SQL 语法有错误;检查与您的 mysql 服务器版本相对应的手册,以在第 4 行的“/ COUNT(status)) FROM Requests”附近使用正确的语法
【问题讨论】:
只是为了澄清您想要查找具有status
列且值为A
的行的百分比?
为您提供方便,向我们展示一些示例表数据和预期结果(均为格式化文本,无图像。)minimal reproducible example
您使用 DBMS SQL Server 标记了您的请求,但错误消息显示 DBMS 是 MySQL。这是两种不同的产品。我已经更改了标签。
我已将您的图片链接替换为文字。请阅读这里,为什么我们通常不喜欢图片:meta.***.com/questions/285551/…。
【参考方案1】:
您似乎想要状态为 A 的行数,然后是所有行数,然后是它们的比率。
select
count(*) as total,
count(case when status = 'A' then 1 end) as collected,
count(case when status = 'A' then 1 end) * 100.0 / count(*) as percentage
from requests;
您的语法错误解释:
SELECT Total -- there is no column called total in the subquery
FROM
(
SELECT Collected -- there is no column called expression in the subquery
FROM
(
SELECT COUNT(status) -- This is okay. You could also simply use COUNT(*).
FROM Requests AS Collected -- You alias the table as collected here, not the count expression
WHERE status = "A" -- "A" would be a column (or column alias). A string literal has single quotes instead: 'A'.
) / COUNT(status) -- We are at the end of the FROM clause here. You cannot use / in the FROM clause.
)
FROM Requests -- We are still in the main query, which has a FROM clause already. It is not allowed to have two FROM clauses.
【讨论】:
【参考方案2】:最简单的方法是平均:
SELECT AVG(CASE WHEN status = 'A' THEN 100.0 ELSE 0 END) as percentage_of_a
FROM Requests;
这等价于,但短于:
SELECT SUM(CASE WHEN status = 'A' THEN 100.0 ELSE 0 END) / COUNT(*) as percentage_of_a
FROM Requests;
【讨论】:
以上是关于选择列的百分比的主要内容,如果未能解决你的问题,请参考以下文章