按百分比订购汇总结果?

时间:2014-10-13 13:03:46

标签: mysql sql select aggregate

我的表'产品':

id:
1
2
3
4

我的另一张表' productSet'

id / specification
1  / 1
1  / n
1  / n
1  / n
1  / 1
2  / 1
2  / n
2  / n
3  / 1
3  / n
3  / n
3  / 1
3  / n
3  / n
3  / n
4  / 1
4  / n
4  / n
4  / 1

product.id = productSet.id

count(productSet WHERE id LIKE '1') = 5
count(productSet WHERE id LIKE '1' AND specification LIKE 'n') = 3
percent = (100-((3*100)/5)) = 40%

count(productSet WHERE id LIKE '2') = 3
count(productSet WHERE id LIKE '2' AND specification LIKE 'n') = 2
percent = (100-((2*100)/3)) = 33,33%

count(productSet WHERE id LIKE '3') = 7
count(productSet WHERE id LIKE '3' AND specification LIKE 'n') = 5
percent = (100-((5*100)/7)) = 28,57%

count(productSet WHERE id LIKE '4') = 4
count(productSet WHERE id LIKE '4' AND specification LIKE 'n') = 2
percent = (100-((2*100)/4)) = 50%

我需要结果DESC

4 (50%)
1 (40%)
2 (33,33%)
3 (28,57)

请帮我这个命令。我不知道从哪里开始。

1 个答案:

答案 0 :(得分:0)

这是一个简单的聚合查询。 GROUP BYSUM()COUNT()的良好使用可以为您提供准确的答案,而且非常有效。 http://sqlfiddle.com/#!2/95546c/8/0

SELECT id, 
       COUNT(*) AS total_count, 
       SUM(specification <> 'n') AS non_n_count,
       100.0 * SUM(specification <> 'n') / COUNT(*) AS percent
  FROM productSet
 GROUP BY id
 ORDER BY 4 DESC

这里的技巧是要意识到表达式specification <> 'n'为表中的每一行产生的值为0或1,其中非NULL值为specification。因此,总结这些值可以得到符合标准的行数。

ORDER BY 4 DESC命令结果集按降序排列第四列。