参考我之前的问题:
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
谢谢
答案 0 :(得分:3)
您的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
答案 1 :(得分:-1)
试试这个
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