簡體   English   中英

按列SQL獲取計數百分比

[英]Getting the percentage of count by column SQL

我有一個名為 stats 的表,其中包含所有內容(項目約束),這是我們有區域的概念 = 一個區域有多個“分組”一個分組有多個“Resultat_Appel”我想通過以下方式獲得每個“分組”的百分比區域(通過計算“Id_Externe”,這意味着每個區域的計數百分比總和 = 100%,grp1 + grp2 + ... = 100% 這是我的查詢(它正在工作,但是當我使用 distinct 時,它不是),我需要從計數中刪除重復的“Id_Externe”

沒有區別

   select st.Nom_Region,
   st.Groupement,
   count(st.Id_Externe)                                   as count,
   count(st.Id_Externe) * 100 / (select count(st2.Id_Externe)
                                 from stats as st2
                                 where st2.Nom_Region like st.Nom_Region
                                   and st2.Nom_Region is not null
                                   and st2.Resultat_Appel not like "=%"
                                   and st2.Groupement not like "Non Renseigné"
                                   and st2.Groupement not like "Appels post"
                                 group by st2.Nom_Region) as percent
from stats as st
where st.Nom_Region is not null
  and st.Resultat_Appel not like "=%"
  and st.Groupement not like "Non Renseigné"
  and st.Groupement not like "Appels post"

group by st.Nom_Region, st.Groupement
order by st.Nom_Region

使用不同的

    select st.Nom_Region,
   st.Groupement,
   count(distinct st.Id_Externe)                                   as count,
   count(distinct st.Id_Externe) * 100 / (select count(distinct st2.Id_Externe)
                                          from stats as st2
                                          where st2.Nom_Region like st.Nom_Region
                                            and st2.Nom_Region is not null
                                            and st2.Resultat_Appel not like "=%"
                                            and st2.Groupement not like "Non Renseigné"
                                            and st2.Groupement not like "Appels post"
                                          group by st2.Nom_Region) as percent
from stats as st
where st.Nom_Region is not null
  and st.Resultat_Appel not like "=%"
  and st.Groupement not like "Non Renseigné"
  and st.Groupement not like "Appels post"

group by st.Nom_Region, st.Groupement
order by st.Nom_Region

這是在 Id.Externe 上不使用“distinct”的結果圖像(OK)

在此處輸入圖片說明

這是在 Id.Externe 上使用“distinct”的結果圖像(不正確)

在此處輸入圖片說明

如果我理解正確,您只需要窗口函數:

select st.Nom_Region, st.Groupement,
       count(*) as count,
       count(*) * 100.0 / sum(count(*)) over (partition by st.Nom_Region) as percentage
from stats st
where st.Nom_Region is not null and
      st.Resultat_Appel not like '=%' and
      st.Groupement not like 'Non Renseigné' and
      st.Groupement not like 'Appels post'
group by st.Nom_Region, st.Groupement
order by st.Nom_Region;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM