-1

Refer to my previous Questions:

Get count of items and their values in one column

Get count percent of a record in a single query

How I can get percentage of intervals? such this example:

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

thanks

Community
  • 1
  • 1
Arian
  • 12,793
  • 66
  • 176
  • 300

2 Answers2

3

Your Intervals table could be a TVP in SQL Server 2008.

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  
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
-1

Try this

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
Sparky
  • 14,967
  • 2
  • 31
  • 45