我有一个返回数据的查询,如下所示:
ID Date Date_flag
1 10-07/10/2016 1
1 1-06/10/2016 2
1 11-07/11/2016 3
1 12-07/13/2016 4
1 13-07/14/2016 5
2 10-07/10/2016 1
2 11-07/11/2016 2
2 12-07/13/2016 3
2 13-07/14/2016 4
2 14-07/15/2016 5
我在SSRS中创建一个矩阵,其中Column group基于Date
,Row group基于ID
,数据用于计算行数。所以这是我的数据在SSRS矩阵中的样子:
H_Level 10-07/10/2016 1-06/10/2016 11-07/11/2016 12-07/13/2016 13-07/14/2016 14-07/15/2016
1 1 0 1 1 1 0
2 1 1 1 1 1 1
现在我遇到的问题是我一次只能在一个矩阵中有三列。所以我的矩阵应该分成两个矩阵(在这种情况下)。我需要让它变得动态,因为将来我可以有更多的日期,这意味着更多的列。如何创建动态矩阵并使其每3列中断?当矩阵中断时,我希望标题再次显示。这在SSRS中是否可行?
答案 0 :(得分:0)
你可以像下面那样进行调整:
Select * from (
Select Id, [Date], 1 as Val from YourDates ) a
pivot (max([Val]) for [date] in ([10-07/10/2016],[1-06/10/2016 ],[11-07/11/2016],[12-07/13/2016],[13-07/14/2016],[14-07/15/2016]) ) p
对于动态列列表,您可以按如下方式查询:
declare @cols1 varchar(max)
declare @cols2 varchar(max)
declare @query nvarchar(max)
Select @cols1 = stuff((Select Distinct ','+QuoteName([Date]) from YourDates for xml path('')),1,1,'')
Select @cols2 = stuff((Select Distinct ','+'COALESCE('+QuoteName([Date])+', 0) as ' + QuoteName([Date]) from YourDates for xml path('')),1,1,'')
Select @Query = ' Select Id, ' + @cols2 + ' from (
Select Id, [Date], 1 as Val from YourDates ) a
pivot (max([Val]) for [date] in (' + @cols1 + ') ) p'
--Select @Query
exec sp_executesql @Query
输出如下
+----+---------------+---------------+---------------+---------------+---------------+---------------+
| Id | 10-07/10/2016 | 1-06/10/2016 | 11-07/11/2016 | 12-07/13/2016 | 13-07/14/2016 | 14-07/15/2016 |
+----+---------------+---------------+---------------+---------------+---------------+---------------+
| 1 | 1 | 1 | 1 | 1 | 1 | 0 |
| 2 | 1 | 0 | 1 | 1 | 1 | 1 |
+----+---------------+---------------+---------------+---------------+---------------+---------------+
答案 1 :(得分:0)
我认为隐藏的问题是表的可能长度。如果是这样,为什么不切换H_Level和Id的列。你将循环开始约会。
这样你只有3列,数据的长度也不会有问题。