如何划分两个SELECT语句以获得SQL的百分比

时间:2018-03-13 21:52:23

标签: sql oracle

我正在尝试计算来自交货表的皇家邮件发送的商品百分比。

DataFrame.groupby

我收到错误说

  

“SQL命令未正确结束”。

对此的任何帮助都会很棒!谢谢!

6 个答案:

答案 0 :(得分:2)

 Select post_method, (Count(post_method)* 100 / (Select Count(*) From 
 delivery_tbl)) as percentage
 From delivery_tbl
 Where post_method = 'RM'
 Group By post_method

答案 1 :(得分:2)

您可以使用条件聚合执行此操作,如下所示:

SELECT round (100 * (count(case when post_method = 'RM' then 1 end) / count(*)), 2) royal_mail_items_percentage
FROM   delivery_tbl;

我已经添加了round功能,因为您看起来只想显示最多2个小数位。

使用条件聚合进行查询意味着您只需要查询一次表,因此它应该比其他答案更高效,这些答案需要多次点击表。

答案 2 :(得分:1)

SELECT ((SELECT post_method FROM delivery_tbl Where post_method = 'RM')/ (SELECT post_method FROM delivery_tbl))*100 as royalperc

更新了查询以获取计数

 SELECT ((SELECT COUNT(post_method) FROM delivery_tbl Where post_method = 'RM')/ (SELECT COUNT(post_method) FROM delivery_tbl))*100 as royalperc

我相信你应该使用第二个查询

答案 3 :(得分:1)

您正在对2个查询进行划分,但为了正确显示结果,您需要添加该部门的SELECT声明。

这是错误的:

-- Result: SQL command not properly ended
(SELECT 100 FROM DUAL) / (SELECT 50 FROM DUAL)

没关系:

-- Result: 2
SELECT
    (SELECT 100 FROM DUAL) / (SELECT 50 FROM DUAL)
FROM 
    DUAL

您还应该尝试添加列名,以便更清楚:

-- ResultOfDivision: 2
SELECT
    (SELECT 100 FROM DUAL) / (SELECT 50 FROM DUAL) ResultOfDivision 
FROM
    DUAL

请记住,在子查询之间执行这些类型的分割(或任何算术运算)时,每个子查询必须返回1行。如果他们不这样做,那么SQL引擎将不知道要使用哪一行并抛出错误。

-- Result: single-row subquery returns more than one row.
SELECT
    (SELECT 100 FROM DUAL) / (SELECT SomeColumn FROM YourTableWithManyRows) ResultOfDivision 
FROM 
    DUAL

对于最后一个示例,正确的表达式将是以下(对于每一行)。

SELECT
    (100 / SomeColumn) ResultOfDivision 
FROM
    YourTable
WHERE
    SomeColumn <> 0 -- Prevent division by 0!!

对于您的情况,似乎您正在尝试查看以下内容:

-- Make sure SELECT COUNT(1) FROM delivery_tbl isnt 0!

SELECT
    post_method,
    COUNT(post_method) * 100 / (SELECT COUNT(1) FROM delivery_tbl) 100perc, -- 100 based percentage
    COUNT(post_method) / (SELECT COUNT(1) FROM delivery_tbl) 1perc -- 1 based percentage
FROM
    delivery_tbl
GROUP BY
    post_method

答案 4 :(得分:0)

在开头添加 SELECT 语句:

SELECT ((SELECT post_method FROM delivery_tbl Where post_method = 'RM') / (SELECT post_method FROM delivery_tbl));

答案 5 :(得分:0)

使用sql:

select (
(select sum(post_method) from delivery_tbl where post_method = 'RM') /
(select sum(post_method) from delivery_tbl)) * 100 as "royalperc" from dual ;