Mysql查询配置

Mysql query configuration

我有这个查询并且运行完美,我只是想缩短结果以帮助我快速阅读:

SELECT numbers 
FROM vista 
WHERE id IN (
    SELECT b.id + 3 FROM(
      SELECT t1.id, t1.numbers t1val, t2.numbers t2val
      FROM vista t1 
      JOIN vista t2 ON t1.id = t2.id-1 
      JOIN vista t3 ON t1.id = t3.id-2 
      WHERE t1.id = (SELECT MAX(id) - 2 FROM vista)
    ) a
    JOIN (
      SELECT t1.id, t1.numbers t1val, t2.numbers t2val, t3.numbers t3val 
      FROM vista t1 
      JOIN vista t2 ON t1.id = t2.id-1 
      JOIN vista t3 ON t1.id = t3.id-2 
      WHERE t1.id < (SELECT MAX(id) - 2 FROM vista)
    ) b 
  ON a.t1val = b.t1val 
  AND a.t2val = b.t2val 
  AND a.t3val = b.t3val 
  AND a.id <> b.id
) 
ORDER BY id;

结果是这样的:

3
5
2
7
5
5
7
3

我怎样才能得到按组和百分比计算的结果:

喜欢:

5 = 3 (37.50%)
7 = 2 (25.00%)
3 = 2 (25.00%)
2 = 1 (12.50%)

好吧,如果你的查询有效,那么你应该做这样的事情来获得你想要的结果:

解决方案一 - 这将为您提供数字、组中的计数和单独列中的百分比...

SELECT numbers, COUNT(numbers), (COUNT(numbers) / (SELECT COUNT(numbers) 
                                 FROM vista
                                 /*your WHERE clause*/)) * 100 AS percent 
FROM vista 
-- your WHERE Statement
GROUP BY numbers
-- your ORDER BY

这是一个 sql fiddle 看看它是什么样的 http://sqlfiddle.com/#!9/08b4e/3

解决方案二 - 这将在一列中给出数字,在组中给出计数数字,在其他列中给出百分比:

 SELECT numbers, CONCAT(CountNum, ' (', percent, '%)') AS counted
 FROM (SELECT numbers, COUNT(numbers) AS CountNum, (COUNT(numbers) / (SELECT COUNT(numbers) 
                                                  FROM vista
                                                  WHERE ID BETWEEN 1 AND 8
                                                  /*your WHERE clause*/)) * 100 AS percent
       FROM vista 
       WHERE ID BETWEEN 1 AND 8
       -- your WHERE clause this is just for a testing purpose
       GROUP BY numbers
       ORDER BY ID) AS srcTable
       -- your ORDER BY clause this is just for a testing purpose

这是 Fiddle http://sqlfiddle.com/#!9/51275/1

当然你需要插入你的 WHERE 子句而不是我的我只是把这个放在测试它。 GL希望能帮到你一点。