【问题标题】:Get count percent of a record in a single query在单个查询中获取记录的计数百分比
【发布时间】:2011-11-12 12:09:24
【问题描述】:

参考这个问题:

Get count of items and their values in one column

如何在单个查询中获得记录计数的百分比,如下所示:

ItemId        count          Percent
------------------------------------
   1            2              33.3
   2            0                0
   3            1              16.6
   4            3              50.0            

谢谢

【问题讨论】:

  • SO post 中的解决方案应该可以帮助您计算百分比。

标签: sql sql-server sql-server-2008


【解决方案1】:

COUNT(*) OVER() 为您提供总数。

编辑但实际上您需要SUM(COUNT(MyTbl.ItemID)) OVER(),因为您正在对该列中的值求和。

SELECT Items.ItemID,
       [count] = COUNT(MyTbl.ItemID),
       [Percent] = 100.0 * COUNT(MyTbl.ItemID) / SUM(COUNT(MyTbl.ItemID)) OVER()
FROM   (VALUES (1,'N1'),
               (2,'N2'),
               (3,'N4'),
               (4,'N5')) Items(ItemID, ItemName)
       LEFT JOIN (VALUES(1),
                        (1),
                        (3),
                        (4),
                        (4),
                        (4)) MyTbl(ItemID)
         ON ( MyTbl.ItemID = Items.ItemID )
GROUP  BY Items.ItemID
ORDER  BY Items.ItemID  

【讨论】:

    【解决方案2】:
    select
        ItemId,
        count(*) as count,
        cast(count(*) as decimal) / (select count(*) from myTable) as Percent 
    from myTable
    group by ItemId
    

    【讨论】:

      【解决方案3】:
      SELECT a.itemid
             , count(a.itemid) as [count]
             , ((cast(count(a.itemid) as decimal) / t.total) * 100) as percentage
      FROM table1 as a
      INNER JOIN (SELECT count(*) as total FROM table1) as t ON (1=1)
      GROUP BY a.item_id, t.total
      ORDER BY a.item_id
      

      【讨论】:

        【解决方案4】:
        SELECT a.itemid, 
            count(a,itemid) as [count], 
            100.00 * (count(a.itemid)/(Select sum(count(*) FROM myTable)) as [Percentage]
         FROM myTable
            Group by a.itemid 
            Order by a.itemid
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-29
          • 2021-02-22
          • 1970-01-01
          相关资源
          最近更新 更多