SQL查询以按打印名称打印职业

时间:2018-09-16 13:33:03

标签: sql oracle subquery

查询按字母顺序排列的职业中所有姓名的列表,紧随其后的是每个职业的第一个字母作为括号(即:括在括号中)。

例如:

AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S)

查询“职业”中每个职业的发生次数。以升序对出现的事件进行排序,并以以下格式输出它们:

SELECT name||'('||SUBSTR(occupation, 1, 1)||')'
FROM occupations
ORDER BY name

UNION

SELECT "There are a total of"|| count(*) from occupations group by occupation;

3 个答案:

答案 0 :(得分:0)

ORDER BY必须是您使用UNION/UNION ALL时的最后一个子句:

SELECT name||'('||SUBSTR(occupation, 1, 1)||')' AS col
FROM occupations
union
select 'There are a total of'|| count(*) 
from occupations 
group by occupation
ORDER BY CASE WHEN col LIKE 'There are a total%' THEN 1 ELSE 0 END, col;

答案 1 :(得分:0)

see output

带有代码的示例输入和输出:

create table ns_occupations(name varchar(20));

insert into NS_OCCUPATIONS values('AActorName');

insert into NS_OCCUPATIONS values('ADoctorName');

insert into NS_OCCUPATIONS values('AProfessorName');

insert into NS_OCCUPATIONS values('ASingerName');


insert into NS_OCCUPATIONS values('ASingerName');

select * from NS_OCCUPATIONS;

SELECT name||'('||SUBSTR(name, 2, 1)||')'  shortname,count(*)  no_of_occupations
FROM ns_occupations
group by name||'('||SUBSTR(name, 2, 1)||')';

output:
ADoctorName(D)  1
AActorName(A)   1
AProfessorName(P)   1
ASingerName(S)  2

答案 2 :(得分:0)

从职业中选择姓名+'('+ left(occupation,1)+')' 按名称排序 联盟 选择“总共有'+ convert(nvarchar,count(occupation))+''+ occupation +'。”来自职业 按职业分组 按计数(占用)排序;