我喜欢以下列方式获取SQL Server查询输出。目前我的输出是:
Class | Student ID | Student Name
------+------------+---------------
121 S1 Test 1
121 S2 Test 2
500 S22 Test a
500 S23 Test b
但我希望以下列方式输出数据 -
Class: 121
--------------------------------
Student ID | Student Name
-----------+---------------
S1 Test 1
S2 Test 2
Class: 500
--------------------------------
Student ID | Student Name
-----------+---------------
S22 Test a
S23 Test b
有人可以帮助我如何实现这些目标?
由于
答案 0 :(得分:1)
虽然我同意SQL不是你做格式化的地方....有时你会被卡住....
本守则
select '121' as Class, 'S1 ' as [Student ID], 'Test 1' as [Student Name] into #test
union select '121', 'S2 ', 'Test 2'
union select '500', 'S22 ', 'Test a'
union select '500', 'S23 ', 'Test b'
;
WITH class
AS (
SELECT DISTINCT class
FROM #test
)
,student
AS (
SELECT class
,(
SELECT STUFF((
SELECT CHAR(13) + t.[Student ID] + space(len('Student ID | ') - len(t.[Student ID])) + [Student Name]
FROM #Test t
WHERE t.[class] = class.[class]
FOR XML PATH('')
,type
).value('.[1]', 'nvarchar(max)'), 1, 1, '')
) AS info
FROM class
)
,theoutput
AS (
SELECT 'Class: ' + class + CHAR(13) + '------------------------' + CHAR(13) + 'Student ID | Student Name' + CHAR(13) + info + CHAR(13) + CHAR(13) AS txt
FROM student c
)
SELECT STUFF((
SELECT CHAR(13) + txt
FROM theoutput
FOR XML PATH('')
,type
).value('.[1]', 'nvarchar(max)'), 1, 1, '')
将生产
Class: 121
------------------------
Student ID | Student Name
S1 Test 1
S2 Test 2
Class: 500
------------------------
Student ID | Student Name
S22 Test a
S23 Test b
答案 1 :(得分:0)
通过使用While循环,我们可以获得所需结果创建的样本数据
IF OBJECT_ID('Tempdb..#TEMP') IS NOT NULL
Drop table #TEMP
;With cte(Class, StudentID, StudentName)
AS
(
SELECT 121,'S1' ,'Test 1' UNION ALL
SELECT 121,'S2' ,'Test 2' UNION ALL
SELECT 500,'S22','Test a' UNION ALL
SELECT 500,'S23','Test b'
)
SELECT * INTO #TEMP FROM CTe
SET NOCOUNT ON
DECLARE @CLassCOUnt INT
,@minID INT
,@maxid INT
,@Sql NVARCHAR(max)
,@SelectQuery INT
DECLARE @Table TABLE (
ID INT IDENTITY
,CLass INT
)
INSERT INTO @Table (CLass)
SELECT DISTINCT Class
FROM #TEMP
SELECT @minID = min(Id)
FROM @Table
SELECT @maxid = MAX(Id)
FROM @Table
WHILE (@minID <= @maxid)
BEGIN
SELECT @SelectQuery = Class
FROM @Table
WHERE ID = @minID
SELECT @Sql = 'SELECT Class, StudentID, StudentName FROM #TEMP WHERE Class=' + CAST(@SelectQuery AS VARCHAR)
PRINT 'Result Of Class:'+ CAST(@SelectQuery AS VARCHAR)+CHAR(13)+CHAR(10)+'------------------------'
PRINT @Sql
EXEC (@Sql)
SET @minID = @minID + 1
END
SET NOCOUNT OFF