参考这个问题:
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
谢谢
解决方法
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)) MyTbl(ItemID) ON ( MyTbl.ItemID = Items.ItemID ) GROUP BY Items.ItemID ORDER BY Items.ItemID