SQL query to print occupation with print name with order

SQL query to print occupation with print name with order



Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses).



For example:


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



Query the number of occurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format:


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

UNION

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






It is not clear what your question is.

– Gordon Linoff
Sep 16 '18 at 13:34






please give sample input and output data

– nikhil sugandh
Sep 17 '18 at 8:15






String constants need to be enclosed in single quotes in SQL, double quotes are for column or table names. docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/…

– a_horse_with_no_name
Sep 17 '18 at 8:23




2 Answers
2



see output



sample input and output with code:


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






@Ankush Rawat is it working??

– nikhil sugandh
Sep 17 '18 at 9:13




ORDER BY has to be last clause when you use UNION/UNION ALL:


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;






@a_horse_with_no_name Thanks, funny thing is that during copy paste from OP's core I changed it inside WHERE clause :)

– Lukasz Szozda
Sep 17 '18 at 14:52


WHERE



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ