用SQL查询查找总百分比

时间:2014-10-08 13:04:18

标签: sql ms-access

SELECT tblItems.ItemType, Count(tblItems.ItemType) AS total
FROM tblItems
WHERE (((tblItems.Pool) BETWEEN 188 AND 218))
GROUP BY tblItems.ItemType;

这是我当前的查询,它打印出一行中的项目以及它们在名为total的另一行中出现的总时间。我希望能够创建另一行,其中百分比是总项目数。我尝试在计数(total/SUM(total)) AS pct_total之后添加,但这不起作用。我得到的错误是"子查询不能在表达式中使用(Sum(total))"

2 个答案:

答案 0 :(得分:2)

这是一种方法:

SELECT i.ItemType, Count(i.ItemType) AS total,
       Count(*) * 1.0 / (select count(*) from tblItems WHERE Pool between 188 and 218) as ratio
FROM tblItems as i
WHERE i.Pool BETWEEN 188 AND 218
GROUP BY i.ItemType;

答案 1 :(得分:1)

您可能需要使用子查询..尝试这样:

select Itemtype,(total/SUM(total)) AS pct_total from
(SELECT tblItems.ItemType as Itemtype, Count(tblItems.ItemType) AS total
FROM tblItems
WHERE (((tblItems.Pool) BETWEEN 188 AND 218))
GROUP BY tblItems.ItemType) as A
Group By A.Itemtype;