介绍 ( Introduction )

In our last two chats, we discussed enterprises that have had financial years that began in July and ended at the end of June. One of our clients works with this fiscal calendar and their financial folks are Excel “Fundi’s” (Fundisa is a Nguni word for “expert”). Many of their reports contain the current month’s sales, in addition, carrying running totals from the beginning of the fiscal year to date. An example may be seen in the screen dump below:

在上两个聊天中,我们讨论了财务年度始于7月至6月底的企业。 我们的一位客户使用此财务日历,他们的财务人员是Excel“ Fundi's”(Fundisa是Nguni的“专家”一词)。 他们的许多报告还包含当月的销售量,此外,还包含从会计年度开始至今的运行总计。 在下面的屏幕转储中可以看到一个示例:

In today’s chat, we shall be concentrating on creating the necessary stored procedure to extract the data so that it may be placed in a Reporting Services matrix (similar to the Excel spreadsheet shown above). In doing so we are going to commit a SQL Server cardinal sin and utilize a small cursor. But then again, we are all adults and as such do not always do what we should. Not so?

在今天的聊天中,我们将专注于创建必要的存储过程以提取数据,以便将其放置在Reporting Services矩阵中(类似于上面显示的Excel电子表格)。 这样做时,我们将犯下SQL Server基本错误,并利用一个小游标 。 但是话又说回来,我们都是成年人,因此并不总是做我们应该做的事情。 不是吗

Without further ado, let’s get started!

事不宜迟,让我们开始吧!

入门 ( Getting started )

SQL Shack financial is an organization that sells widgets to the public. Their fiscal year begins July 1 and ends June 30. Our data table contains a list of their sales from July 1 to present. Our task is to calculate the monthly income (on a monthly basis) and to have an additional column showing the year to date earnings.

SQL Shack financial是一个向公众出售窗口小部件的组织。 他们的会计年度从7月1日开始,到6月30日结束。我们的数据表包含从7月1日到现在的销售清单。 我们的任务是计算每月收入(每月),并有一个附加列显示年初至今的收入。

We begin by having a look at our working data.

我们首先看一下我们的工作数据。

We note that within our data table there are four fields:

我们注意到在我们的数据表中有四个字段:

  • Revenue收入
  • Yearmth 年份
  • Orderdate订购日期
  • Monthee蒙泰

As our reporting is based on the concept of “a month”, the field “Orderdate” will only be utilized as a part of the predicate. “YearMth” however will be utilized as a grouping column.

由于我们的报告基于“一个月”的概念,因此“订单日期”字段将仅用作谓词的一部分。 但是,“ YearMth”将用作分组列。

Opening a new query window, we begin by declaring our stored procedure and a creating a few working variables (see below).

打开一个新的查询窗口,首先声明存储过程并创建一些工作变量(见下文)。

The reader will note that we declared two date variables (@BeginFiscal and @Endfiscal).

读者会注意到,我们声明了两个日期变量(@BeginFiscal和@Endfiscal)。

Additionally we declared twelve variables which will contain the values of “YearMth” for the twelve months of the current fiscal year. Finally we have a small start and end date routine that will ascertain the start and end date of the current fiscal year. See the code snippet below:

此外,我们声明了十二个变量,其中包含当前会计年度的十二个月中的“ YearMth”值。 最后,我们有一个小的开始和结束日期例程,可以确定当前会计年度的开始和结束日期。 请参见下面的代码片段:


declare @decider int
declare @Yearr varchar(4)
set @decider = datepart(Month,convert(date,getdate()))
set @Yearr   = datepart(YEAR,Convert(date,Getdate()))
--
set @Yearr    = case when @decider >= 7 then datepart(YEAR,Convert(date,Getdate())) else @Yearr -1 end
set @Beginfiscal = convert(varchar(4),@Yearr) + '0701'
set @Endfiscal   = dateadd(d,-1,dateadd(Year,1,@beginFiscal))select @BeginFiscal as [Beginning Date],  @endFiscal as [Ending Date]

Now that with the necessary infrastructure in place, we shall calculate the values for our twelve monthly variables.

现在,有了必要的基础架构,我们将计算十二个每月变量的值。

July is calculated as follows:

7月的计算方法如下:


set @month01  =convert(varchar(4),datepart(Year,@beginFiscal)) + case when len(convert(varchar(2),datepart(Month,@beginFiscal))) = 1 then convert(varchar(2),'0' + convert(varchar(2),datepart(Month,@beginFiscal)))  elseconvert(varchar(2),datepart(Month,@beginFiscal))end

If we were to parse this SQL statement, ‘201407’ would be rendered (in February 2015).

如果我们要解析此SQL语句,将呈现“ 201407”(2015年2月)。

The values associated with these 12 variables may be seen in the screenshot below:

与这12个变量关联的值可以在下面的屏幕截图中看到:

The complete code listing may be seen in ADDENDA 1.

完整的代码清单可以在ADDENDA 1中看到。

We are now in a position to calculate the monthly earnings (see below).

我们现在可以计算每月收入(见下文)。

Looking at the screenshot above, we note the monthly sales PLUS some prepaid accounts for March through May (as seen in February 2015). The important point is that we have the monthly totals. The astute reader will note that I placed all the values into a temporary table called “#rawdata1”.

在上面的屏幕截图中,我们注意到3月至5月的月度销售以及一些预付费帐户(如2015年2月所示)。 重要的是我们有每月的总数。 精明的读者会注意到,我将所有值都放入了一个名为“#rawdata1”的临时表中。

Coming from an Oracle world (cursor based), I am about to commit the most serious of SQL Server CRIMES. I am going to utilize a cursor upon the data within the temporary table (in order NOT to lock the proper database table). The reason being to calculate our running total.

来自Oracle世界(基于游标),我将提交最严肃SQL Server CRIMES。 我将在临时表中的数据上使用游标 (以免锁定正确的数据库表)。 原因是要计算我们的总运行量。

In the screen dump above, we declare a table variable called @Revenue. This table variable contains three fields “Revenue1”, “Cumulative” and “YearMth” (see above).

在上面的屏幕转储中,我们声明一个名为@Revenue的表变量。 该表变量包含三个字段“ Revenue1”,“累计”和“ YearMth”(请参见上文)。

声明我们的光标 ( Declaring our cursor )

We are now in a position to create our cursor (see below).

现在,我们可以创建光标了(见下文)。

We first declare three variables: @YearMth which will contain the “YearMth” value from the data. @Revenue which will contain the current month’s revenue figures. @Cumulative will be utilized to contain the running total of revenue for the current year (see above). We initialize @Cumulative = 0.

我们首先声明三个变量:@YearMth,它将包含数据中的“ YearMth”值。 @Revenue,其中将包含当月的收入数字。 @累计将用于包含当年的运行总收入(请参见上文)。 我们初始化@Cumulative = 0。

We are now in a position to declare our cursor (see above).

现在,我们可以声明光标了(见上文)。

创建我们的光标主体 ( Creating our cursor body )


OPEN rt_cursor
FETCH NEXT FROM rt_cursor INTO @Revenue1,@YearMthWHILE @@FETCH_STATUS = 0BEGINbegin Set @Cumulative = @Cumulative + @Revenue1INSERT @Revenue VALUES (@Revenue1,@Cumulative,@YearMTH)endFETCH NEXT FROM rt_cursor INTO @Revenue1,@YearMthEND
CLOSE rt_cursor
DEALLOCATE rt_cursor
SELECT * Into #rawdata2 FROM @Revenue

We note from the code snippet above, that with each iteration through the body of the cursor, @Cumulative is incremented by the current value of @Revenue1. The current YearMth, the current month’s revenue, and the cumulative revenue are all then inserted into our table variable.

我们从上面的代码片段中注意到,通过光标主体的每次迭代,@ Cumulative都会以@ Revenue1的当前值递增。 然后,将当前YearMth,当前月的收入以及累计收入插入到我们的表变量中。

After that last row is retrieved @@FETCH_STATUS will no longer return a “0”, thus on the next pass, we break out of the loop.

在检索到最后一行之后,@@ FETCH_STATUS将不再返回“ 0”,因此在下一次传递时,我们跳出循环。

We then close the cursor and deallocate it and place all the data from the table variable into a temp table called #rawdata2. Why? Hint: Persistence, especially with any “Go” statement which may be executed somewhere “further down” the code.

然后,我们关闭游标并对其进行释放,并将表变量中的所有数据放入名为#rawdata2的临时表中。 为什么? 提示:持久性,尤其是对于任何可能在代码“更进一步”的地方执行的“ Go”语句。

Running our query we obtain the desired results (see above).

运行查询,我们将获得所需的结果(请参见上文)。

我们当前的困境 ( Our current dilemma )

The format in which the data has been rendered (see above), whilst conducive to a chart or graph, is not conducive to populating a Reporting Services matrix. This said we must massage the data utilizing a pivot construct (see below).

呈现数据的格式(请参见上文),虽然有利于图表或图形,但不利于填充Reporting Services矩阵。 这表示我们必须利用数据透视构造来整理数据(请参见下文)。

We begin by declaring an additional variable @NSQL nvarchar(2000). We shall want to execute a T-SQL statement within our code utilizing “exec sp_executesql” and for this to work, the statement must be in NVARCHAR format.

我们首先声明一个附加变量@NSQL nvarchar(2000)。 我们将要在代码中使用“ exec sp_executesql ”执行T-SQL语句,为了使其正常工作,该语句必须为NVARCHAR格式。

This said the reader will note that we construct a PIVOT SQL statement and assign this to the variable “NSQL”. Within the statement, we utilize the “YearMth” variables that we created above, in addition to utilizing the “YearMth” values from the table.

这表示读者会注意到,我们构造了一个PIVOT SQL语句并将其分配给变量“ NSQL”。 在该语句中,除了利用表中的“ YearMth”值外,我们还利用上面创建的“ YearMth”变量。

This done, we create an additional temporary table which we call #rawdata55.

完成此操作后,我们将创建另一个临时表,我们将其称为#rawdata55。

Temporary table #rawdata55 will hold the pivoted data which will eventually feed our report matrix.

临时表#rawdata55将保存数据透视表,这些数据最终将馈入我们的报告矩阵。

With this achieved, we are in a position to execute the SQL statement (contained within our “NSQL” variable) and load the data into our temporary table “#rawdata55”.

通过实现这一目标,我们可以执行SQL语句(包含在“ NSQL”变量中)并将数据加载到临时表“#rawdata55”中。

Executing the query (as is) renders the following data (see below).

执行查询(按原样)将呈现以下数据(请参见下文)。

将我们的查询用于报告目的 ( Utilizing our query for reporting purposes )

Bringing up SQL Server Data Tools, we are going to create a new Reporting Services project to display our data in a matrix format.

调出SQL Server数据工具,我们将创建一个新的Reporting Services项目,以矩阵格式显示我们的数据。

We give our “Report Server Project” the name “AggregationAndPivot” (see above). We click OK to continue.

我们将“ Report Server Project”命名为“ AggregationAndPivot”(请参见上文)。 我们单击“确定”继续。

Our first task is to create a “Shared Data Source”. Right-clicking on the “Shared Data Sources” folder, we select “Add” and then “Add New Data Source” from the context menu.

我们的首要任务是创建一个“共享数据源”。 右键单击“共享数据源”文件夹,我们从上下文菜单中选择“添加”,然后选择“添加新数据源”。

The “Shared Data Source Properties” dialog box is brought into view.

将显示“共享数据源属性”对话框。

We give our “Shared Data Source” a name and point it to our “SQLShackFinancial” database. We then test the connection and find that all is in order (see above). We click “OK” to create our shared dataset.

我们给“共享数据源”命名,然后将其指向“ SQLShackFinancial”数据库。 然后,我们测试连接并发现一切正常(请参见上文)。 我们单击“确定”以创建我们的共享数据集。

As always, should you not be certain on how to create data sources, datasets and reports, please do have a look at my SQL Shack article entitled:

与往常一样,如果您不确定如何创建数据源,数据集和报表,请查看我SQL Shack文章,标题为:

“Now you see it, now you don’t”.
/now-see-now-dont/

“现在您看到了,现在您不知道了”。
/ now-see-now-dont /

We are now in a position to create our one and only report for this “get together”. By right-clicking on the “Reports” folder. We select “Add” and “New Item” from the context menu.

我们现在可以为此“聚在一起”创建唯一的报告。 通过右键单击“ Reports”文件夹。 我们从上下文菜单中选择“添加”和“新项目”。

We create a new report which we call “Matrix01”. We then click “Add”.

我们创建一个称为“ Matrix01”的新报告。 然后,我们单击“添加”。

Once on our report drawing surface (see above), we right click upon the “Datasets” folder and select “Add Dataset” from the context menu (see above).

进入报告绘图图面(参见上文)后,我们右键单击“ Datasets”文件夹,然后从上下文菜单中选择“ Add Dataset”(参见上文)。

The “Dataset Properties” dialog is brought up and we give our new dataset the name “MatrixData”. We must now define a local data source. We click on the “New” button (see above and to the right).

出现“数据集属性”对话框,我们给新数据集命名为“ MatrixData”。 现在,我们必须定义一个本地数据源。 我们单击“新建”按钮(参见上方和右侧)。

The “Data Source Properties” dialogue box is brought up. We give our local data source the name “MatrixDataSource” and link it to our shared data source “MatrixDS” (see above). We click OK to leave the “Data Source Properties” box and find ourselves back on the “Dataset Properties” page.

出现“数据源属性”对话框。 我们将本地数据源命名为“ MatrixDataSource”,并将其链接到共享数据源“ MatrixDS”(请参见上文)。 我们单击“确定”以离开“数据源属性”框,然后回到“数据集属性”页面。

We set our “Query type” to “Stored Procedure” and select the “SQLShackAggregation” procedure from the drop-down list (see above). This is the query that we just created, which is now being utilized as a stored procedure.

我们将“查询类型”设置为“存储过程”,然后从下拉列表中选择“ SQLShackAggregation”过程(请参见上文)。 这是我们刚刚创建的查询,现在已被用作存储过程。

Having accepted our “SQLShackAggregation” stored procedure as our source of data, we click the “Refresh Fields” button (see above). We then click on the “Fields” tab.

在接受“ SQLShackAggregation”存储过程作为数据源之后,我们单击“刷新字段”按钮(请参见上文)。 然后,我们单击“字段”选项卡。

We note that all of the fields that we added to our SQL query are now present in our dataset (see above). We click OK to leave the “Dataset Properties” dialogue box.

我们注意到,添加到SQL查询中的所有字段现在都存在于我们的数据集中(请参见上文)。 我们单击“确定”离开“数据集属性”对话框。

Our completed dataset may be seen on the left of the screenshot above.

我们完整的数据集可以在上方屏幕截图的左侧看到。

We place a “Matrix Report Item” onto our report surface (see above).

我们将“矩阵报告项目”放置在报告表面上(见上文)。

and set its “DataSetName” property ( see above and to the bottom right).

并设置其“ DataSetName”属性(请参见上方和右下方)。

We must now remove the column grouping which is achieved by right-clicking on the “ColumnGroup” and selecting “Delete Group” (see above).

现在,我们必须删除通过右键单击“ ColumnGroup”并选择“ Delete Group”(请参见上文)实现的列分组。

As always, we are asked if we wish to “Delete group and related rows and columns” OR “Delete group only”. We select “Delete group only” (see above).

与往常一样,系统会询问我们是否要“删除组以及相关的行和列”或“仅删除组”。 我们选择“仅删除组”(请参见上文)。

Arriving back on our report surface we add eleven additional columns to our matrix (see above).

回到我们的报表表面,我们在矩阵中添加了11个其他列(请参见上文)。

We add the “Name” column (from our query, which is either the monthly or cumulative value) to the first column and then each month’s values to the ensuing columns (see above).

我们将“名称”列(来自我们的查询,是月度值或累计值)添加到第一列,然后将每个月的值添加到随后的列中(请参见上文)。

Tidying things up a bit and adding a bit of color, our report should be similar to the one shown below:

整理一下内容并添加一些颜色,我们的报告应类似于以下所示:

All numeric figures have been changed to currency and right oriented (see above).

所有数字均已更改为货币和右对齐(请参见上文)。

We now double click upon the “Row Group” [name] as we must set the sorting of the rows.

现在,我们必须双击“行组” [名称],因为我们必须设置行的排序。

The “Group Properties” dialog box is brought up (see above). We click the “Sorting” tab.

出现“组属性”对话框(请参见上文)。 我们点击“排序”标签。

We set the sorting on the column “name” to be from “Z to A”. In other words “descending” (see above). We click “OK” to close the dialogue box.

我们将“名称”列上的排序设置为从“ Z到A”。 换句话说,“下降”(见上文)。 我们单击“确定”关闭对话框。

让我们试一下 ( Let us give it a run )

Clicking the “Preview” button, we render our report. Note that two rows are rendered. The first, the monthly revenue and the second row, the year to date. This is exactly what we planned to achieve.

单击“预览”按钮,我们将呈现报告。 请注意,呈现了两行。 第一,每月收入,第二行,年初至今。 这正是我们计划要实现的目标。

结论 ( Conclusions )

In today’s “Get together” we saw that extracting data in the correct format is not always that easy. Running totals are often required in reports and they are easy to achieve via looping or by utilizing a “SQL Server dirty word”, a cursor.

在今天的“聚在一起”中,我们看到以正确的格式提取数据并不总是那么容易。 报表中经常需要运行总计,并且可以通过循环或利用“ SQL Server脏词”(游标)轻松实现总计。

No matter which technique is utilized the data may still be in an in appropriate format and oft times to get our data into the correct format we must “pivot” of data.

无论采用哪种技术,数据都可能处于适当的格式,并且经常要使我们的数据变为正确的格式,我们必须“透视”数据。

This said we have seen how easily our data may be pivoted.

这表示我们已经看到数据轮转的难易程度。

This brings us to the end of today’s “get together”. I hope that I have generated more questions than answers.

这使我们走到了今天的“聚在一起”的终点。 我希望我提出的问题多于答案。

As always, should you have any questions or concerns OR wish to obtain a copy of the code and applications, please do feel free to contact me.

与往常一样,如果您有任何疑问或疑虑,或者希望获得代码和应用程​​序的副本,请随时与我联系。

In the interim, happy programming!

在此期间,编程愉快!

ADDENDA 1 (Stored Procedure listing)

ADDENDA 1 存储过程列表


use [SQLShackFinancial]
go
--IF OBJECT_ID(N'tempdb..#rawdata1') IS NOT NULL
--BEGIN
--     DROP TABLE #rawdata1
--END
--IF OBJECT_ID(N'tempdb..#rawdata2') IS NOT NULL
--BEGIN
--     DROP TABLE #rawdata2
--END
--IF OBJECT_ID(N'tempdb..#rawdata55') IS NOT NULL
--BEGIN
--     DROP TABLE #rawdata55
--ENDcreate procedure SQLShackAggregation
as
declare @beginFiscal date
declare @endFiscal date
declare @month01 varchar(6)
declare @month02 varchar(6)
declare @month03 varchar(6)
declare @month04 varchar(6)
declare @month05 varchar(6)
declare @month06 varchar(6)
declare @month07 varchar(6)
declare @month08 varchar(6)
declare @month09 varchar(6)
declare @month10 varchar(6)
declare @month11 varchar(6)
declare @month12 varchar(6)
declare @decider int
declare @Yearr varchar(4)
set @decider = datepart(Month,convert(date,getdate()))
set @Yearr   = datepart(YEAR,Convert(date,Getdate()))
--
set @Yearr    = case when @decider >= 7 then datepart(YEAR,Convert(date,Getdate())) else @Yearr -1 end
set @Beginfiscal = convert(varchar(4),@Yearr) + '0701'
set @Endfiscal   = dateadd(d,-1,dateadd(Year,1,@beginFiscal))set @month01  =convert(varchar(4),datepart(Year,@beginFiscal)) + case when len(convert(varchar(2),datepart(Month,@beginFiscal))) = 1 then convert(varchar(2),'0' + convert(varchar(2),datepart(Month,@beginFiscal)))  elseconvert(varchar(2),datepart(Month,@beginFiscal))endset @month02  =convert(varchar(4),datepart(Year,@beginFiscal)) + case when len(convert(varchar(2),datepart(Month,dateadd(mm,1,@beginFiscal))))  = 1 then convert(varchar(2),'0' + convert(varchar(2),datepart(Month,dateadd(mm,1,@beginFiscal))))  elseconvert(varchar(2),datepart(Month,dateadd(mm,1,@beginFiscal)))end   set @month03  =convert(varchar(4),datepart(Year,@beginFiscal)) + case when len(convert(varchar(2),datepart(Month,dateadd(mm,2,@beginFiscal))))  = 1 then convert(varchar(2),'0' + convert(varchar(2),datepart(Month,dateadd(mm,2,@beginFiscal))))  elseconvert(varchar(2),datepart(Month,dateadd(mm,2,@beginFiscal)))end   set @month04  =convert(varchar(4),datepart(Year,@beginFiscal)) + case when len(convert(varchar(2),datepart(Month,dateadd(mm,3,@beginFiscal))))  = 1 then convert(varchar(2),'0' + convert(varchar(2),datepart(Month,dateadd(mm,3,@beginFiscal))))  elseconvert(varchar(2),datepart(Month,dateadd(mm,3,@beginFiscal)))end   set @month05  =convert(varchar(4),datepart(Year,@beginFiscal)) + case when len(convert(varchar(2),datepart(Month,dateadd(mm,4,@beginFiscal))))  = 1 then convert(varchar(2),'0' + convert(varchar(2),datepart(Month,dateadd(mm,4,@beginFiscal))))  elseconvert(varchar(2),datepart(Month,dateadd(mm,4,@beginFiscal)))end   set @month06  =convert(varchar(4),datepart(Year,@beginFiscal)) + case when len(convert(varchar(2),datepart(Month,dateadd(mm,5,@beginFiscal))))  = 1 then convert(varchar(2),'0' + convert(varchar(2),datepart(Month,dateadd(mm,5,@beginFiscal))))  elseconvert(varchar(2),datepart(Month,dateadd(mm,5,@beginFiscal)))end   set @month07  =convert(varchar(4),datepart(Year,@endFiscal)) + case when len(convert(varchar(2),datepart(Month,dateadd(mm,-5,@endFiscal))))  = 1 then convert(varchar(2),'0' + convert(varchar(2),datepart(Month,dateadd(mm,-5,@endFiscal))))  elseconvert(varchar(2),datepart(Month,dateadd(mm,-5,@endFiscal)))end set @month08  =convert(varchar(4),datepart(Year,@endFiscal)) + case when len(convert(varchar(2),datepart(Month,dateadd(mm,-4,@endFiscal))))  = 1 then convert(varchar(2),'0' + convert(varchar(2),datepart(Month,dateadd(mm,-4,@endFiscal))))  elseconvert(varchar(2),datepart(Month,dateadd(mm,-4,@endFiscal)))end
set @month09  =convert(varchar(4),datepart(Year,@endFiscal)) + case when len(convert(varchar(2),datepart(Month,dateadd(mm,-3,@endFiscal))))  = 1 then convert(varchar(2),'0' + convert(varchar(2),datepart(Month,dateadd(mm,-3,@endFiscal))))  elseconvert(varchar(2),datepart(Month,dateadd(mm,-3,@endFiscal)))end
set @month10  =convert(varchar(4),datepart(Year,@endFiscal)) + case when len(convert(varchar(2),datepart(Month,dateadd(mm,-2,@endFiscal))))  = 1 then convert(varchar(2),'0' + convert(varchar(2),datepart(Month,dateadd(mm,-2,@endFiscal))))  elseconvert(varchar(2),datepart(Month,dateadd(mm,-2,@endFiscal)))end set @month11  =convert(varchar(4),datepart(Year,@endFiscal)) + case when len(convert(varchar(2),datepart(Month,dateadd(mm,-1,@endFiscal))))  = 1 then convert(varchar(2),'0' + convert(varchar(2),datepart(Month,dateadd(mm,-1,@endFiscal))))  elseconvert(varchar(2),datepart(Month,dateadd(mm,-1,@endFiscal)))end
set @month12  =convert(varchar(4),datepart(Year,@endFiscal)) + case when len(convert(varchar(2),datepart(Month,dateadd(mm,0,@endFiscal))))  = 1 then convert(varchar(2),'0' + convert(varchar(2),datepart(Month,dateadd(mm, 0,@endFiscal))))  elseconvert(varchar(2),datepart(Month,dateadd(mm,0,@endFiscal)))end select sum(Revenue) as Revenue,Yearmth into #rawdata1from [dbo].[AggregatesAndTotals]where [Orderdate] between @beginFiscal and @endFiscalgroup by yearmthorder by yearmthDECLARE @Revenue TABLE (Revenue decimal(15,2),Cumulative decimal(15,2), YearMth varchar(6))DECLARE @SolutionsArea Varchar(100),@YearMth Varchar(6),@Revenue1 decimal(15,2),@Cumulative decimal(15,2)Set @Cumulative = 0DECLARE rt_cursor CURSOR
FOR Select Revenue, YearMth from #rawdata1
Order By YearMTH
OPEN rt_cursor
FETCH NEXT FROM rt_cursor INTO @Revenue1,@YearMthWHILE @@FETCH_STATUS = 0BEGINbegin Set @Cumulative = @Cumulative + @Revenue1INSERT @Revenue VALUES (@Revenue1,@Cumulative,@YearMTH)endFETCH NEXT FROM rt_cursor INTO @Revenue1,@YearMthEND
CLOSE rt_cursor
DEALLOCATE rt_cursorSELECT * Into #rawdata2 FROM @RevenueDeclare @NSQL nvarchar(2000)set @Nsql =
' select  name, [' +  @month01+ '],[' + @month02+ '],[' +@month03+ '],[' +@month04+ '],[' +@month05 +'],[' + @month06+ '],[' +@month07+ '],[' +@month08+ '],[' +@month09+ '],[' +@month10+ '],[' +  @month11+ '],[' +@month12 +
']   from ' +
' ( ' +
'  select Yearmth, name, value ' +
'  from #rawdata2 ' +
'  unpivot ' +
'  ( ' +
'    value for name in ([Revenue],[Cumulative]) ' +
--Ensure the [Revenue], {Cumulative] etc. are of the same data format or you will generate a run --time error (see above)
'  ) unpiv '+
' ) src ' +
' pivot ' +
' ( ' +
'  sum(value) ' +
'  for YearMth in (['  + @month01+ '],[' + @month02+ '],[' +@month03+ '],[' +@month04+ '],[' +@month05 +'],[' + @month06+ '],[' +@month07+ '],[' +@month08+ '],[' +@month09+ '],[' +@month10+ '],['  + @month11+ '],[' +@month12  +'] )) piv ' + '  order by name asc ' CREATE TABLE #rawdata55([name] [varchar](75) NULL,[Month01] [decimal](15, 2) NULL,[Month02] [decimal](15, 2) NULL,[Month03] [decimal](15, 2) NULL,[Month04] [decimal](15, 2) NULL,[Month05] [decimal](15, 2) NULL,[Month06] [decimal](15, 2) NULL,[Month07] [decimal](15, 2) NULL,[Month08] [decimal](15, 2) NULL,[Month09] [decimal](15, 2) NULL,[Month10] [decimal](15, 2) NULL,[Month11] [decimal](15, 2) NULL,[Month12] [decimal](15, 2) NULL
)insert #rawdata55
exec sp_executesql @NSQL with recompile
select * from #rawdata55
order by name desc

翻译自: https://www.sqlshack.com/using-cursor-correctly-extract-sql-server-data-place-in-reporting-services/

使用游标正确提取SQL Server数据并将其放置在Reporting Services矩阵中相关推荐

  1. 2008 server sql 数据库引擎安装失败;安装2008sql server时,提示sql server 复制、数据库引擎服务、Reporting Services、全文搜索等失败。W10

    由于学习C#,需要使用数据库,我本人亲身体验了安装N次失败的绝望,也在网上找了许多方法,但是又没有效果,也很是无奈,最后抱着一点点希望,也下了很大决心----重置电脑 会删错我的所有软件,但是不会删除 ...

  2. sql数据库查询聚合函数_如何使用SQL Server数据质量服务确保正确的数据聚合

    sql数据库查询聚合函数 介绍 (Introduction) An interesting opportunity arose at a client site during early Octobe ...

  3. 学习SQL:SQL Server数据透视表

    In the previous few articles in this series, we've set the foundations on how to create a report. We ...

  4. sql azure 语法_使用Azure Data Studio从SQL Server数据创建图表

    sql azure 语法 In this article, we will explore charts in an Azure Data Studio using data stored in SQ ...

  5. 实验10 SQL Server 数据备份/恢复

    实验10 SQL Server 数据备份/恢复 一.实验目的 1.了解数据库备份的过程和属性设置: 2.掌握应用企业管理器备份和恢复数据库: 3.掌握应用T-SQL备份和恢复数据库: 4.掌握数据导入 ...

  6. SQL Server商业智能功能– SQL Server数据工具–商业智能

    介绍 (Introduction) 在上一篇有关introduction to SQL Server business intelligence we covered the general stru ...

  7. 使用SQL Server数据工具和Visual Studio Online进行连续部署

    In the previous posts 在以前的帖子中 Deployment to several databases using SQL Server Data Tools and TFS us ...

  8. 如何使用SQL Server数据工具中的“可见性”选项降低报告的复杂性

    介绍 (Introduction) Far too often we encounter clients that are really too keen to establish all inclu ...

  9. 浅析SQL Server数据修复命令DBCC的使用

    SQL Server数据库提供了修复命令DBCC,当SQL Server数据库遭到质疑或者是有的无法完成读取时可以尝试用此命令来修复.以下是一些常见的DBCC修复命令,希望会给读者带来帮助.    1 ...

最新文章

  1. JDK动态代理和CGLIB代理的区别
  2. 2018 年,NLP 研究与应用进展到什么水平了?
  3. 4-1:C/C++内存管理
  4. 智能优化算法:磷虾群算法-附代码
  5. mysql和memcache 查询_使用Memcache缓存MySQL查询(转载)
  6. vue启动项目报错 `webpack-dev-server --inline --progress --config build/webpack.dev.conf
  7. 2020年 2月 省市区sql(一)
  8. c#进度条刻度_自定义刻度jQuery进度条及插件
  9. 空洞卷积(Dilated Convolution)简介
  10. WinRAR下载官方免费版
  11. win10 永久删除自带微软拼音输入法
  12. 无线路由器和有线路由器桥接
  13. java短信验证码_java实现发送短信验证码
  14. python colormap_Python matplotlib的使用并自定义colormap的方法
  15. unity-单例模式
  16. 如何给PDF设置可跳转目录的2种方法
  17. 能解决 80% 需求的 10个 CSS动画库
  18. CentOS 部署 NodeBB
  19. matlab 产生高斯噪声和高斯白噪声方法
  20. PCA降维方法及在ATT人脸数据集的应用实例

热门文章

  1. python语言的变量特点随时_python程序设计——基本语言特性
  2. SpokenEnglish01_ When's it due?
  3. PTA L2-006 树的遍历-二叉树的后序遍历+中序遍历,输出层序遍历 团体程序设计天梯赛-练习集...
  4. TCP/IP系列——长连接与短连接的区别
  5. 超清晰 ,一文理解:深拷贝与浅拷贝(js)
  6. 【零基础学Java】—Collections集合工具类(四十二)
  7. jQuery学习(四)— jQuery的ready事件和原生JS的load事件的区别
  8. 美团信用卡现金分期怎么还?
  9. 五千的手机和两三千的手机使用起来有什么不一样?有必要买贵的吗?
  10. 大家有没有发现,女生带上口罩后,感觉颜值升高了,尤其眼睛好看?