【问题标题】:Get percent of an interval using single query使用单个查询获取间隔百分比
【发布时间】:2011-09-10 18:41:02
【问题描述】:

参考我之前的问题:

Get count of items and their values in one column

Get count percent of a record in a single query

如何获得间隔百分比?比如这个例子:

  ItemId        count          Percent 
 ------------------------------------    
   1-2            2              33.3    
   3-4            4              66.6

谢谢

【问题讨论】:

  • 使用子查询。子查询将汇总所有计数列,您可以使用这些列来根据每个单独项目/行的计数计算百分比。
  • 或者先把总和存入一个局部变量,然后写一个正则查询,用每行的计数除以数字。
  • 区间从何而来?
  • 用户要求一些间隔,例如:1-2、3-4、4-5,超过 5

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


【解决方案1】:

您的Intervals 表可能是 SQL Server 2008 中的 TVP。

SELECT Intervals.ItemId,
       [count] = COUNT(MyTbl.ItemID),
       [Percent] = 100.0 * COUNT(MyTbl.ItemID) / SUM(COUNT(MyTbl.ItemID)) OVER()
FROM   (VALUES(NULL,0, 'Less than 1'),
              (1,2,'1-2'),
              (3,4,'3-4'),
              (6,NULL,'More than 4')) Intervals (Low, High, ItemId)
       LEFT JOIN (VALUES(1),
                        (1),
                        (3),
                        (4),
                        (4),
                        (4)) MyTbl(ItemID)
         ON ( MyTbl.ItemID BETWEEN ISNULL(Intervals.Low, -2147483648) AND
                                        ISNULL(Intervals.High, 2147483647) )
GROUP  BY Intervals.ItemId,
          Intervals.Low
ORDER  BY Intervals.Low  

【讨论】:

    【解决方案2】:

    试试这个

    select itemId,count(*),(count(*)/xx.Tot)*100 as Percent
    from tableName a
    join (select sum(count) as Tot from tableName) xx on 1=1
    group by ItemID
    

    【讨论】:

    • 请先看我引用的链接
    • 对不起,错过了间隔部分。你可以用 case 语句来做到这一点,但看起来你已经找到了解决方案......
    猜你喜欢
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 2019-08-12
    • 2021-01-29
    • 2021-11-12
    相关资源
    最近更新 更多