使用自定义列的SQL查询

时间:2014-11-26 23:56:36

标签: sql sql-server tsql

我试图在SQL Server中编写一个查询,它会给我一些关于我所拥有的表的信息。我有2张表/样本数据:

pid     surname gender
196     Kelly   F
248     Hoskin  M
375     Walker  M

pid     title                   is_doctoral
196     Master of Science       1
248     Doctor of Philosophy    0

我想要的结果是对男性和女性信息的一些分析:

结果

Gender      # Students  Doctorate Degrees Held      Master Degrees Held         Graduation Rate
Males       2           1                           0                           50%
Females     1           0                           1                           100%

我无法弄清楚如何在结果表(男性,女性)中创建自定义第一列,我不知道如何进行条件求和。我是SQL的初学者,非常感谢任何帮助。有人可以创建一个查询来获得该结果吗?如果我看到查询,我将能够从那里了解它。

2 个答案:

答案 0 :(得分:2)

试试这个:

示例数据

create table person(
    pid int,
    surname varchar(50),
    gender char(1)
)
create table degree(
    pid int,
    title varchar(50),
    is_doctoral varchar(5)
)
insert into person values
(196, 'Kelly', 'F'),
(248, 'Hoskin', 'M'),
(375, 'Walker', 'M')
insert into degree values
(196, 'Master of Science', 'TRUE'),
(248, 'Doctor of Philosophy', 'FALSE');

<强>解

select
    case when p.gender = 'F' then 'Female' else 'Male'end as Gender,
    count(*) as [# of Students],
    sum(case when d.is_doctoral = 'TRUE' then 1 else 0 end) as [Doctorate Degrees Held],
    sum(case when d.is_doctoral = 'FALSE' then 1 else 0 end) as [Masters Degrees Held],
    convert(varchar(10), (cast((count(d.pid) * 1.0)/count(*) * 100 as decimal))) + '%' as [Graduation Rate]
from person p
left join degree d
    on d.pid = p.pid
group by p.gender
order by p.gender desc

答案 1 :(得分:0)

我相信您正在寻找case statement

SELECT
CASE gender
  WHEN 'M' THEN 'Male'
  WHEN 'F' THEN 'Female'
END as string_gender
FROM person;