用子查询计算百分比

时间:2011-11-23 14:34:38

标签: mysql sql subquery

我正在尝试计算SQL查询中的百分比。

这就是我现在所拥有的:

SELECT
DATE(processed_at) AS day,
(
  SELECT
  COUNT(*) FROM return_items
  WHERE return_id IN (SELECT id FROM returns WHERE DATE(processed_at) = day)
) as products_returned,
COUNT(*) as return_count,
(
  SELECT
  COUNT(*) as co_returns
  FROM returns
  WHERE return_method = 'mondial_relais'
  AND DATE(processed_at) = day
) as return_rate_mr
FROM returns
WHERE MONTH(processed_at) = 10
AND YEAR(processed_at) = 2011
GROUP BY day;

基本上我需要return_rate_mr为百分比值。 我尝试过像return_rate_mr * 100 / return_count as perc_value这样的事情,但这不起作用。 (我实际上并不需要当前的return_rate_mr值,只需要百分比。

有什么想法吗?

4 个答案:

答案 0 :(得分:0)

你在找这个吗?

SELECT
  `day`,
  `products_returned`,
  (`return_rate_mr` * 100) / `return_count` AS `percentage`
FROM (
  SELECT
  DATE(processed_at) AS day,
  (
    SELECT
    COUNT(*) FROM return_items
    WHERE return_id IN (SELECT id FROM returns WHERE DATE(processed_at) = day)
  ) as products_returned,
  COUNT(*) as return_count,
  (
    SELECT
    COUNT(*) as co_returns
    FROM returns
    WHERE return_method = 'mondial_relais'
    AND DATE(processed_at) = day
  ) as return_rate_mr
  FROM returns
  WHERE MONTH(processed_at) = 10
  AND YEAR(processed_at) = 2011
  GROUP BY day) AS `ss`

答案 1 :(得分:0)

您尝试过类似的事情吗?

SELECT (`return_rate_mr` * 100 ) / `return_count` as "yourValue", OthersFields
 FROM SELECT
DATE(processed_at) AS day,
(
  SELECT
  COUNT(*) FROM return_items
  WHERE return_id IN (SELECT id FROM returns WHERE DATE(processed_at) = day)
) as products_returned,
COUNT(*) as return_count,
(
  SELECT
  COUNT(*) as co_returns
  FROM returns
  WHERE return_method = 'mondial_relais'
  AND DATE(processed_at) = day
) as return_rate_mr
FROM returns
WHERE MONTH(processed_at) = 10
AND YEAR(processed_at) = 2011
GROUP BY day;

希望这有帮助

答案 2 :(得分:0)

假设您的原始查询返回了所需的结果,您可以将其包装为子查询:

SELECT
    day,
    return_rate_mr * 100 / return_count as perc_value,
    ... any other columns ...
FROM
    ( ... your original query here ...) as myalias;

基本上,子查询会创建一个重命名列的结果集。然后,外部查询可以自由使用这些新列名。

答案 3 :(得分:0)

尝试:

SELECT DATE(processed_at) AS day,
       count(distinct id) as products_returned,
       COUNT(*) as return_count,
       100* sum(case return_method when 'mondial_relais' then 1 end) / COUNT(*) 
                as return_perc_mr
FROM returns
WHERE MONTH(processed_at) = 10
AND YEAR(processed_at) = 2011
GROUP BY day;

我怀疑products_returned应该计算不同的item_id值(或类似的东西),但这应该复制原始查询中的逻辑。