How can I assign a normal table from a dynamic piv

2019-01-29 11:42发布

问题:

I need to make a report in Stimulsoft from the last 12 months from our current date, I used dynamic pivot table to make this, the original table is at figure 1

Then the pivot table is like the figure 2 (bigger image link here: http://i.stack.imgur.com/LPCuP.jpg)

The DACP_Value at figure 1 is the row at the date it corresponds at figure 2. Note that the culture is set to pt-BR (brazil)

Here is a sample code of the generation of the pivot table made in SQLFiddle

http://www.sqlfiddle.com/#!3/3205a/23

I need to put this dynamic data with the headers inside a normal table (it can be a temporary table) so I can use it in my report query and be recognized by the Stimulsoft software.

回答1:

Add INTO YourTable after the SELECT on your code:

DECLARE @Col NVARCHAR(MAX) = 
    (   SELECT  ', ' + QUOTENAME(CONVERT(VARCHAR, DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP) - (12 - Number), 0), 103)) + ' = [' + CAST(number AS VARCHAR) + ']'
        FROM    Master..spt_values
        WHERE   Type = 'P'
        AND     number BETWEEN 0 AND 12
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')


DECLARE @SQL NVARCHAR(MAX) = 
        N'WITH Data AS
        (   SELECT  DACP_ID,
                    DACP_Value,
                    [MonthNum] = 12 - DATEDIFF(MONTH, DACP_Date, CURRENT_TIMESTAMP)
            FROM    yourtable
            WHERE   DATEDIFF(MONTH, DACP_Date, CURRENT_TIMESTAMP) BETWEEN 0 AND 12
        )   
        SELECT  DACP_ID' + @Col + '
        INTO YourTable --Add this line here
        FROM    Data
                PIVOT
                (   SUM(DACP_Value)
                    FOR MonthNum IN ([0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
                ) pvt;'

EXECUTE SP_EXECUTESQL @SQL


回答2:

As a way, you can use the master-detail report in Stimulsoft tool. As master table you can use the table with date only:

SELECT CONVERT(DATE, DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP) - (12 - Number), 0), 103) AS DT,
       CONVERT(VARCHAR(2),MONTH(DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP) - (12 - Number), 0))) + CONVERT(VARCHAR(4),YEAR(DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP) - (12 - Number), 0))) As MonthYear
  FROM Master..spt_values
 WHERE Type = 'P'
       AND number BETWEEN 0 AND 12

The detail table it's "yourTable" with additional column:

select *, convert(varchar(2),Month(DACP_date)) + convert(varchar(4),Year(DACP_date)) as MonthYear from yourtable

realtion on MonthYear columns. In report you can use the Cross-Data component for master data, and DataBand component for detail data. Please see the image from the following link: http://imgur.com/Ve03BXU



回答3:

Also this is a solution for the case when the amount of data for each date is the same, ie ID for each date are the same. If not, one may have to add more conditions for showing headers on the left side.