例子:https://blog.csdn.net/wikey_zhang/article/details/76849826
DECLARE @limitDay INT;
SET @limitDay = 35;
IF DATEDIFF(DAY, '2018-03-21 00:00:00', '2018-03-26 00:00:00') > @limitDay
BEGIN
RETURN;
END;
DECLARE @ReportID INT= 3;
DECLARE @BeginDateTime DATETIME= '2018-03-21 00:00:00';
DECLARE @EndDateTime DATETIME= '2018-03-26 00:00:00';
DECLARE @DataParam VARCHAR(50)= NULL;
EXEC dbo.Proc_GetReportData @ReportID, @BeginDateTime, @EndDateTime,@DataParam;
DECLARE @sql VARCHAR(5000)
SELECT @sql = ISNULL(@sql + ',', '') + '[' + PropertyText + ']'
FROM RPT_ReportProperty WITH ( NOLOCK )
WHERE ReportID =3
AND StatusFlag = 1
SELECT @sql
------------------------------------------------------------------------------------
USE [Tr.TWX]
GO
/****** Object: StoredProcedure [dbo].[Proc_GetReportData] Script Date: 2018/3/26 9:52:32 ******/
SET ANSI_NULLS ON
GO
DECLARE @ReportID VARCHAR(5)='3'
DECLARE @BeginDateTime VARCHAR(25) = '2018-03-21 00:00:00'
DECLARE @EndDateTime VARCHAR(25)='2018-03-26 00:00:00'
DECLARE @DataParam VARCHAR(50)=NULL
DECLARE @sql VARCHAR(5000)
SELECT @sql = ISNULL(@sql + ',', '') + '[' + PropertyText + ']'
FROM RPT_ReportProperty WITH ( NOLOCK )
WHERE ReportID = @ReportID
AND StatusFlag = 1
IF @DataParam IS NULL OR @DataParam=''
BEGIN
SET @sql = 'select ' + @sql
+ ' from(SELECT DataDate,PropertyText,DataValue FROM RPT_ReportProperty p WITH(NOLOCK) JOIN RPT_ReportData d WITH(NOLOCK) ON p.PropertyID=d.PropertyID WHERE d.ReportID='''
+ @ReportID + ''' AND DataDate>= ''' + @BeginDateTime
+ ''' AND DataDate< ''' + @EndDateTime
+ ''')tb pivot (max(DataValue) for PropertyText in (' + @sql
+ '))a'
END
ELSE
BEGIN
SET @sql = 'select ' + @sql
+ ' from(SELECT DataDate,PropertyText,DataValue FROM RPT_ReportProperty p WITH(NOLOCK) JOIN RPT_ReportData d WITH(NOLOCK) ON p.PropertyID=d.PropertyID WHERE d.ReportID='''
+ @ReportID + ''' AND DataDate>= ''' + @BeginDateTime
+ ''' AND DataDate< ''' + @EndDateTime
+ ''' AND DataParam= ''' + @DataParam
+ ''')tb pivot (max(DataValue) for PropertyText in (' + @sql
+ '))a'
END
PRINT @sql
-- EXEC(@sql)
-----------------------------------------------------------------------------------------------
SELECT [月份] ,
[日期] ,
[入库单量] ,
[入库及时率] ,
[延误入库单量] ,
[异常入库单量]
FROM ( SELECT DataDate ,
PropertyText ,
DataValue
FROM RPT_ReportProperty p WITH ( NOLOCK )
JOIN RPT_ReportData d WITH ( NOLOCK ) ON p.PropertyID = d.PropertyID
WHERE d.ReportID = '3'
AND DataDate >= '2018-03-21 00:00:00'
AND DataDate < '2018-03-26 00:00:00'
) tb PIVOT ( MAX(DataValue) FOR PropertyText IN ( [月份], [日期],
[入库单量], [入库及时率],
[延误入库单量],
[异常入库单量] ) ) a;
SELECT TOP 30 * FROM RPT_ReportData ORDER BY DataDate DESC
SELECT TOP 30 * FROM RPT_ReportProperty p
SELECT TOP 30 DataDate ,
PropertyText ,
DataValue
FROM RPT_ReportProperty p WITH ( NOLOCK )
JOIN RPT_ReportData d WITH ( NOLOCK ) ON p.PropertyID = d.PropertyID
注:数据格式在百度云 TWX下的 数据格式与内容.xls
-----------------------------------------------------------------------------------------------------------------------