代码之家  ›  专栏  ›  技术社区  ›  Rod

SQL查询:对于每个值,确定包含该值的行的百分比?

  •  0
  • Rod  · 技术社区  · 15 年前

    我举个简单的例子:

    ContactName, NoteCount
    John, 100
    Rob, 10 
    Amy, 10
    Chris, 10
    

    请用外行的话解释一下我想做什么。

    2 回复  |  直到 12 年前
        1
  •  4
  •   Samuel Neff    15 年前

    如果您真的想知道确切人数所占的百分比,请使用:

    SELECT
        NoteCount,
        COUNT(*) ContactsWithThisNoteCount,
        COUNT(*) / (SELECT COUNT(*) FROM Contacts) PercentageContactsWithThisNoteCount
    FROM 
        Contacts
    GROUP BY
        NoteCount
    

        2
  •  1
  •   remi bourgarel    15 年前
    select 
    ((countTen/countTotal)*100) as percentTen,
    ((countHundred/countTotal)*100) as percentHundred
    FROM (
      select 
      cast(sum(case when noteCount <= 10 then 1 else 0 end) as float) as countTen,
      cast(sum(case when noteCount <= 100 and > 10 then 1 else 0 end) as float) as countHundred,
      cast(count(*) as float) as countTotal
      from
      contacts
    ) temp
    

    应该没问题,我经常使用技巧和+情况时,我需要做一个过滤器计数