Is it safe to use a (broken?) GROUP BY to calculate percentages?

时间:2015-06-30 19:26:35

标签: sql group-by percentage

Newbie question. I have this table A:

theDate     |  concept    |  datum
DATE        |  VARCHAR    |  FLOAT
----------------------------------
2000-01-01  |  Concept A  |  19
2000-01-01  |  Concept B  |  10
2000-01-01  |  Concept C  |  0
2001-01-01  |  Concept A  |  30
2001-01-01  |  Concept B  |  15
2001-01-01  |  Concept C  |  0

I need to calculate the percentages:

theDate     |  concept    |  percentage
DATE        |  VARCHAR    |  FLOAT
----------------------------------
2000-01-01  |  Concept A  |  65.51724138
2000-01-01  |  Concept B  |  34.48275862
2000-01-01  |  Concept C  |  0
2001-01-01  |  Concept A  |  66.66666667
2001-01-01  |  Concept B  |  33.33333333
2001-01-01  |  Concept C  |  0

Is it safe to use a single GROUP BY, without a subquery or a self JOIN? Like this:

SELECT theDate, concept, datum * 100 / sum(datum) percentage
FROM A
GROUP BY theDate

Note: I've reviewed this question Calculate percentage in SQL but I feel it doesn't answer mine.

1 个答案:

答案 0 :(得分:1)

正确的方法是这个..但在mysql中它不会给出任何错误......

SELECT theDate, concept, datum * 100 / sum(datum) percentage
FROM A
GROUP BY (theDate,concept)