您需要 PIVOT 数据,如果您使用的是 SQL-Server 2008 或更高版本,您可以使用 PIVOT 函数:
CREATE TABLE #T (Employee INT, Group_name VARCHAR(50))
INSERT #T VALUES (81, 'BNEEO55'), (81, 'BNELLIG'), (81, 'LPKAPE'), (81, 'HRFT'), (90, 'BNRETINV')
SELECT Employee,
COALESCE([BNEEO55],'No') AS [BNEEO55],
COALESCE([BNELLIG],'No') AS [BNELLIG],
COALESCE([BNRETINV],'No') AS [BNRETINV],
COALESCE([HRFT],'No') AS [HRFT],
COALESCE([LPKAPE],'No') AS [LPKAPE]
FROM ( SELECT *, 'Yes' [Data]
FROM #T
) d
PIVOT
( MAX(Data)
FOR Group_Name IN ([BNEEO55], [BNELLIG], [BNRETINV], [HRFT], [LPKAPE])
) pvt
但是,如果您的数据正在更改,听起来您需要动态地执行此操作。像下面这样的东西会起作用:
DECLARE @SQL NVARCHAR(MAX) = '',
@Cols NVARCHAR(MAX) = ''
SELECT @SQL = @SQL + ',' + QUOTENAME(Group_Name),
@Cols = @Cols + ',COALESCE(' + QUOTENAME(Group_Name) + ',''No'') AS ' + QUOTENAME(Group_Name)
FROM ( SELECT DISTINCT Group_Name
FROM #T
) T
SET @SQL = '
SELECT Employee, ' + STUFF(@Cols, 1, 1, '') +
'FROM ( SELECT *, ''Yes'' [Data]
FROM #T
) d
PIVOT
( MAX(Data)
FOR Group_Name IN (' + STUFF(@SQL, 1, 1, '') + ')
) pvt'
EXECUTE SP_EXECUTESQL @SQL
这构建了与第一个相同的查询,但意味着当添加新的组名时,不必更改查询。
编辑
要创建并调用它作为存储过程:
CREATE TABLE T (Employee INT, Group_name VARCHAR(50))
INSERT T VALUES (81, 'BNEEO55'), (81, 'BNELLIG'), (81, 'LPKAPE'), (81, 'HRFT'), (90, 'BNRETINV')
GO
CREATE PROCEDURE PivotT
AS
DECLARE @SQL NVARCHAR(MAX) = '',
@Cols NVARCHAR(MAX) = ''
SELECT @SQL = @SQL + ',' + QUOTENAME(Group_Name),
@Cols = @Cols + ',COALESCE(' + QUOTENAME(Group_Name) + ',''No'') AS ' + QUOTENAME(Group_Name)
FROM ( SELECT DISTINCT Group_Name
FROM T
) T
SET @SQL = '
SELECT Employee, ' + STUFF(@Cols, 1, 1, '') +
'FROM ( SELECT *, ''Yes'' [Data]
FROM T
) d
PIVOT
( MAX(Data)
FOR Group_Name IN (' + STUFF(@SQL, 1, 1, '') + ')
) pvt'
EXECUTE SP_EXECUTESQL @SQL
GO
EXECUTE PivotT