枢轴SQL查询输出

时间:2018-10-09 09:34:21

标签: sql sql-server tsql pivot

我有一个要求,我的查询将返回类似以下的输出:

PermissionType  IsAllowed
-------------------------
IsEdit        |  1
IsDelete      |  0
isRemove      |  1
isPrint       |  1
isReport      |  0
--            |  -
--            |  -
--            |  -
--------------------------

这些行可以是动态的,具体取决于我将通过的过滤条件。

所以现在我要将上面的结果集转换为以下内容:

IsEdit | IsDelete | IsRemove | IsPrint | IsReport | -- | -- | --
--------------------------------------------------------------------
1      | 0        | 1        | 1       | 0        | -  | -  | -

我尝试在此处使用数据透视表,但是它要求将“列名”透视到输出中,在我的情况下这是动态的,而且它需要FOR的聚合函数,但是我没有任何计算就我而言。

任何人都可以帮助我。

2 个答案:

答案 0 :(得分:1)

然后尝试此动态sql

IF OBJECT_ID('dbo.temp')IS NOT NULL
DROP TABLE temp
;WITH Cte(PermissionType, IsAllowed)
AS
(
SELECT 'IsEdit'   ,  1 UNION ALL
SELECT 'IsDelete' ,  0 UNION ALL
SELECT 'isRemove' ,  1 UNION ALL
SELECT 'isPrint'  ,  1 UNION ALL
SELECT 'isReport' ,  0
)
SELECT  *,ROW_NUMBER()OVER(ORDER BY (SELECT 1)) AS Seq INTO 
temp FROM Cte

DECLARE @Sql nvarchar(max),
        @Sqlcol  nvarchar(max),
        @ISNULLSqlcol nvarchar(max)

SELECT  @Sqlcol=STUFF((SELECT   ', '+QUOTENAME(PermissionType) 
                FROM temp  ORDER BY Seq FOR XML PATH ('')),1,1,'')

SELECT  @ISNULLSqlcol=STUFF((SELECT   ', '+'MAX('+QUOTENAME(PermissionType) +') AS '+QUOTENAME(PermissionType)
                FROM temp ORDER BY Seq FOR XML PATH ('')),1,1,'')

SET @Sql='
        SELECT '+@ISNULLSqlcol+'
        FROM(
        SELECT * FROM temp
        )AS SRC
        PIVOT 
        (
        MAX(IsAllowed) FOR PermissionType IN ('+@Sqlcol+')
        ) AS PVT '
PRINT @Sql
EXEC (@Sql)

IsEdit  IsDelete    isRemove    isPrint isReport
--------------------------------------------------
1         0             1           1       0

答案 1 :(得分:0)

使用pivot和动态sql,您可以创建一个查询,其中将包含不同数量的列:

if OBJECT_ID('Test') is not null 
drop table [dbo].[Test] 

CREATE TABLE [dbo].[Test](PermissionType varchar(20), IsAllowed int)

insert into [dbo].[Test] values
 ('IsEdit'  , 1)
,('IsDelete', 0)
,('isRemove', 1)
,('isPrint' , 1)
,('isReport', 0)

--this variable holds all the dates that will become column names 
declare @permissionTypes nvarchar(max) = '' 

--this variable contains the TSQL dinamically generated
declare @sql nvarchar(max) = ''  

select @permissionTypes = @permissionTypes + ', ' + quotename(PermissionType) 
from [dbo].[Test]  

set @permissionTypes = RIGHT(@permissionTypes, len(@permissionTypes)-2) 

set @sql = concat(
 'select *
    from [dbo].[Test]  
    pivot 
    ( 
    max(isallowed) 
    for PermissionType in (', @permissionTypes, ') 
    ) piv '
 )
 exec(@sql)

结果:

enter image description here

添加新行:

insert into [dbo].[Test] values
 ('IsNew'  , 1)

导致要创建一个新列:

enter image description here