Calculate the percentage in the same SELECT in a query

I am trying to calculate the percentage in the same SELECT in a query of a table in the SQL database.

In the table below, column 3 would have the function of taking the total sum of column 2 *** (15973,1748209 + 1947,18266487 = 17830,35749) *** and dividing by the value of the respective line (in the case of line 1 it is divide by 15913,1748209), but I still can't, can someone help me? Thank you very much in advance

enter image description here

SELECT
    Tab_Dados_Escolha.Parametro,
    Sum(Tab_Dados_Escolha.Metrica) As Metrica,
    Sum(Tab_Dados_Escolha.Metrica) / < % total % > As Porcentagem
FROM
    Tab_Dados_Escolha
WHERE
    (
        Tab_Dados_Escolha.E3TimeStamp >= #<%inicio%>#  
        AND Tab_Dados_Escolha.E3TimeStamp <= #<%fim%># 
    )
GROUP BY
    Tab_Dados_Escolha.Parametro

Upvotes: 0

Views: 72

Answers (2)

eshirvana
eshirvana

Reputation: 24568

Here is how you can do it using a window function:

SELECT
  Tab_Dados_Escolha.Parametro,
  sum(Tab_Dados_Escolha.Metrica) As Metrica,
  sum(Tab_Dados_Escolha.Metrica) * 100.0 / sum(sum(Tab_Dados_Escolha.Metrica)) over() As Porcentagem
FROM Tab_Dados_Escolha
WHERE    
   Tab_Dados_Escolha.E3TimeStamp >= #<%inicio%>#  
   AND Tab_Dados_Escolha.E3TimeStamp <= #<%fim%># 
GROUP BY Tab_Dados_Escolha.Parametro

Upvotes: 1

Dale K
Dale K

Reputation: 27226

I think you want to use the sum() over () window function.

SELECT Tab_Dados_Escolha.Parametro
    , SUM(Tab_Dados_Escolha.Metrica) AS Metrica
    , SUM(Tab_Dados_Escolha.Metrica)/SUM(Tab_Dados_Escolha.Metrica) OVER (PARTITION BY Tab_Dados_Escolha.Parametro) AS Porcentagem
FROM Tab_Dados_Escolha
WHERE (Tab_Dados_Escolha.E3TimeStamp >= #<%inicio%># AND Tab_Dados_Escolha.E3TimeStamp <= #<%fim%>#) 
GROUP BY Tab_Dados_Escolha.Parametro;

Upvotes: 1

Related Questions