您的要求并不完全清楚,但如果我理解您的问题,您可以使用PIVOT函数来获得结果。
如果您的查询数量有限,则此查询的基本语法如下pagenos
:
select groupid, [101105], [100100]
from
(
select pageno, groupid,
flag = 'X'
from yourtable
) d
pivot
(
max(flag)
for pageno in ([101105], [100100])
) piv;
请参阅SQL Fiddle with Demo。
然后,如果您有未知数量的值,则需要使用动态 SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(pageno)
from yourtable
group by pageno
order by pageno
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT groupid, ' + @cols + '
from
(
select pageno, groupid,
flag = ''X''
from yourtable
) x
pivot
(
max(flag)
for pageno in (' + @cols + ')
) p '
execute sp_executesql @query;
请参阅SQL Fiddle with Demo。两个版本都会给出结果:
| GROUPID | 100100 | 101105 |
| gentry | X | X |
| mpadilla | X | X |
| test | X | (null) |
编辑,如果您有要替换的空值,那么我将创建第二个列名列表,该列表将用于最终选择列表,它将包括coalesce
替换空值。代码将是:
DECLARE @cols AS NVARCHAR(MAX),
@colsNull AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(pageno)
from yourtable
group by pageno
order by pageno
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colsNull = STUFF((SELECT ', coalesce(' + QUOTENAME(pageno) +', '''') as '+QUOTENAME(pageno)
from yourtable
group by pageno
order by pageno
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT groupid, ' + @colsNull + '
from
(
select pageno, groupid,
flag = ''X''
from yourtable
) x
pivot
(
max(flag)
for pageno in (' + @cols + ')
) p '
execute sp_executesql @query;
请参阅SQL Fiddle with Demo。结果将是:
| GROUPID | 100100 | 101105 |
| gentry | X | X |
| mpadilla | X | X |
| test | X | |