Get percent of an interval using single query
Refer to my previous Questions:
Get count of items and their开发者_Python百科 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
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
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
精彩评论