在sql server中执行COUNT和PERCENTAGE的最佳方法是什么?

时间:2013-01-05 19:20:01

标签: sql sql-server-2008 sql-server-2005

我有3个字段名,年龄,性别和同意。

同意有两种类型的价值 - 同意和不同意。

我想做的是获得COUNT和%的年龄和性别,他们同意以及COUNT和%的年龄和性别与未达成一致的价值。

我们希望布局类似于:

AGE           GENDER            AGREED
93 600  40%   Female 700 62%   Agreed
   1300 60%          320 38%   Not Agreed

首先,请记住我刚刚编写了数字,但是从上面的示例中,我试图展示我们想要的布局。

每个年龄段都有2套价值观。那些同意的人和他们的百分比是那些没有达成协议价值及其百分比的人的COUNT。

与性别相同。

我希望这不会令人困惑。

以下是我正在使用的代码,但我相信自己走错了路。

提前多多感谢。

Select gender, age, agreed, count(agreed)totalAgreed,Agreed = convert(VARCHAR,convert(MONEY,100.0 * count(agreed) /(SELECT count(agreed) FROM   myTable)), 1) + '%' 

From myTable
Group By gender, age, agreed

2 个答案:

答案 0 :(得分:0)

您只需按性别和年龄进行汇总即可获得计数。您可以根据需要使用条件聚合。以下查询将计数和百分比作为数字。

select gender, age, count(*) as cnt,
       sum(case when agreed = 'Agreed' then 1 else 0 end) as NumAgreed,
       sum(case when agreed = 'NotAgreed' then 1 else 0 end) as NotAgreed,
       avg(case when agreed = 'Agreed' then 1.0 else 0 end) as NumAgreedRatio,
       avg(case when agreed = 'NotAgreed' then 1.0 else 0 end) as NotAgreedRatio
from myTable
group by gender, age

表单与您想要的表格略有不同。这也有用吗?此外,我没有费心将数字转换为百分数,因为我喜欢将数字保持为数字。

答案 1 :(得分:0)

看看这个SQL小提琴:

http://sqlfiddle.com/#!3/9cc6d/9

--Returns count of agreed by gender:
SELECT Gender, Agreed, COUNT(*) as [Count]
FROM MyTable GROUP BY Agreed, Gender;

--Returns count of agreed overall:
SELECT Agreed, COUNT(*) as [Count]
FROM MyTable GROUP BY Agreed;

--Returns count of agreed by gender with percentages
With Overall as (SELECT CAST(COUNT(*) AS FLOAT) as [Count] FROM MyTable)
    SELECT mt.Gender, mt.Agreed, COUNT(*) as [Count], CAST(COUNT(*) AS FLOAT) / o.Count as [Percentage]
FROM MyTable mt
    CROSS JOIN Overall o
GROUP BY mt.Agreed, mt.Gender, o.Count; 

这应该让你开始。

如果要将数据集转换为单行,您可以在表示层中处理它,手动为每列执行子选择,或者使用SQL的PIVOT功能,您可以在此处了解:{{ 3}}