0

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

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

我想要做的是获得同意的 COUNT 和 % 的年龄和性别,以及具有 Not Agreed 值的 COUNT 和 % 的年龄和性别。

我们希望布局类似于:

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

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

每个年龄将有 2 组值。同意的人数及其百分比未同意的人数及其百分比。

与性别相同。

我希望这不会令人困惑。

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

提前非常感谢。

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
4

2 回答 2

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

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

于 2013-01-05T19:26:43.220 回答
0

看看这个 SQL Fiddle:

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 功能,您可以在此处了解:http://nycdotnet .blogspot.com/2012/07/pattern-for-pivot.html

于 2013-01-05T19:39:45.090 回答