Sql 当我不使用';我不想使用聚合?
我正在尝试处理如何将表数据转换成更具视觉吸引力的格式以供输出。这可能是问题的一部分,因为我想要的可能是用于单独的报告软件 我有一张像这样的桌子Sql 当我不使用';我不想使用聚合?,sql,sql-server,sql-server-2008,tsql,pivot-without-aggregate,Sql,Sql Server,Sql Server 2008,Tsql,Pivot Without Aggregate,我正在尝试处理如何将表数据转换成更具视觉吸引力的格式以供输出。这可能是问题的一部分,因为我想要的可能是用于单独的报告软件 我有一张像这样的桌子 teacher student ---------------------- teacher1 Bob teacher1 Jim teacher2 Sam teacher3 Bill teacher3 John teacher3 Eric 我想要一张像这样的桌子: teacher1 teacher2 teach
teacher student
----------------------
teacher1 Bob
teacher1 Jim
teacher2 Sam
teacher3 Bill
teacher3 John
teacher3 Eric
我想要一张像这样的桌子:
teacher1 teacher2 teacher3
---------------------------------
Bob Sam Bill
Jim null John
null null Eric
DECLARE @teacherList AS VARCHAR(max)
SELECT @teacherList = Stuff((SELECT DISTINCT',[' + teacher + ']'
FROM myTable
FOR xml path('')), 1, 1, '')
DECLARE @dynamic_pivot_query AS VARCHAR(max)
SET @dynamic_pivot_query = 'select' + @teacherList +
'from
(
SELECT [teacher],[student]
FROM [dbo].[myTable]
) as S
Pivot
(
MIN([student])
FOR teacher IN (' + @teacherList + ')
) as P
'
EXEC(@dynamic_pivot_query)
因此,我尝试将所有教师姓名填充到一个变量中,然后使用一个Pivot
,但由于我必须选择一个聚合,因此我只能得到Max
或Min
学生,如下所示:
teacher1 teacher2 teacher3
---------------------------------
Bob Sam Bill
Jim null John
null null Eric
DECLARE @teacherList AS VARCHAR(max)
SELECT @teacherList = Stuff((SELECT DISTINCT',[' + teacher + ']'
FROM myTable
FOR xml path('')), 1, 1, '')
DECLARE @dynamic_pivot_query AS VARCHAR(max)
SET @dynamic_pivot_query = 'select' + @teacherList +
'from
(
SELECT [teacher],[student]
FROM [dbo].[myTable]
) as S
Pivot
(
MIN([student])
FOR teacher IN (' + @teacherList + ')
) as P
'
EXEC(@dynamic_pivot_query)
其结果是:
teacher1 teacher2 teacher3
---------------------------------
Bob Sam Bill
假设:
这种方法正是正确的。实际上,我现在正在处理同一类型的代码(这很有趣)。您可以使用
行数
获得您想要的结果
SET @dynamic_pivot_query = 'select ' + @teacherList +
'from
(
SELECT [teacher],[student], row_number() over(partition by teacher order by student) as rn
FROM [dbo].[myTable]
) as S
Pivot
(
MIN([student])
FOR teacher IN (' + @teacherList + ')
) as P
'
更新:要删除SQL注入漏洞,应使用
quotename
正确引用字段列表
SELECT @teacherList = Stuff((SELECT DISTINCT',' + quotename(teacher)
FROM myTable
FOR xml path('')), 1, 1, '')
你最好也希望小鲍比·泰尔斯(Bobby Tables)没有长大成为一名教师。这很容易受到SQL注入的攻击。@SteveKass-谢谢你指出这一点。我已经更新了答案。