简体   繁体   中英

Formatting SQL output

I have written an SQL Server procedure that I would like to have print the department name and students name (in a numbered list) that belong to the department.

The formatting should look like the attached sample snippet and there are two columns involved (students and departments)

The below code is what I have so far - information is mostly correct but the formatting is off and the print statement does not run.

CREATE PROCEDURE pro_depart    
AS    
BEGIN

PRINT '************Procedure pro_department_report************'

SELECT (dd.DNAME) AS Department, STRING_AGG(ss.sname, ', ') WITHIN GROUP (ORDER BY ss.sname DESC) AS Students
FROM STUDENT s
JOIN DEPARTMENT d ON dd.DEPTid = ss.DEPT_ID
GROUP BY dd.DNAME
ORDER BY d.DNAME ASC;

END

在此处输入图像描述

How about a grouping statement with a rollup clause?

Sample data

create table department
(
  deptId int,
  name nvarchar(20)
);

insert into department (deptId, name) values
(1, 'Overachievers'),
(2, 'Some department'),
(3, 'Weird group');

create table student
(
  deptId int,
  name nvarchar(20)
);

insert into student (deptId, name) values
(1, 'A. Alison'),
(2, 'B. Barnes'),
(2, 'C. Caldwell'),
(3, 'D. Duncan');

Solution

If some if these functions are new, then you can look them up in the documentation ( with rollup , grouping , coalesce ). Add , grouping(d.name), grouping(s.name) to the select field list to see where some ranges and sorts are coming from.

select coalesce(s.name, '***' + d.name + '***') as Report
from department d
join student s
  on s.deptId = d.deptId
group by d.name, s.name with rollup
having grouping(d.name) = 0
order by d.name, grouping(s.name) desc;

Result

Yes, every line is a separate row in the SSMS result tab, but you can copy-paste the rows to your favorite text editor and get line breaks after each row (as intended).

Report
---------------------
***Overachievers***
A. Alison
***Some department***
B. Barnes
C. Caldwell
***Weird group***
D. Duncan

Fiddle to see it in action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM