2011-09-07 67 views
7

指這個問題算創紀錄的百分比:獲取單個查詢

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    

感謝

+0

事情是在該[SO交]的溶液(http://stackoverflow.com/questions/770579/how-to-calculate-percentage-with-a-sql-statement )應該可以幫助你計算出百分比。 – JW8

回答

12

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), 
         (4)) MyTbl(ItemID) 
     ON (MyTbl.ItemID = Items.ItemID) 
GROUP BY Items.ItemID 
ORDER BY Items.ItemID 
+1

+1我剛剛學到了一些新東西。 –

+1

+1在 – Lamak

3
select 
    ItemId, 
    count(*) as count, 
    cast(count(*) as decimal)/(select count(*) from myTable) as Percent 
from myTable 
group by ItemId 
2
SELECT a.itemid 
     , count(a.itemid) as [count] 
     , ((cast(count(a.itemid) as decimal)/t.total) * 100) as percentage 
FROM table1 as a 
INNER JOIN (SELECT count(*) as total FROM table1) as t ON (1=1) 
GROUP BY a.item_id, t.total 
ORDER BY a.item_id 
0
SELECT a.itemid, 
    count(a,itemid) as [count], 
    100.00 * (count(a.itemid)/(Select sum(count(*) FROM myTable)) as [Percentage] 
FROM myTable 
    Group by a.itemid 
    Order by a.itemid 
+0

之前,我從來沒有看到過這個招數。所有的代碼答案都是不允許的答案。 –