对于数据给定范围sql取数

介绍 ( Introduction )

I recently heard from a lady from overseas who wanted to find a quick and dirty mechanism of extracting data for a given date range (based upon a fiscal year that started July 1st and ended June 30th). The idea interested me and as always, I had to try it out.

我最近收到一位来自海外的女士的消息,她希望找到一种快速而肮脏的机制来提取给定日期范围内的数据(基于从7月1 开始至6月30 结束的会计年度)。 这个想法使我很感兴趣,而且一如既往,我不得不尝试一下。

In today’s “get together”, we are going to have a look at how this may be achieved.

在今天的“聚在一起”中,我们将看看如何实现这一目标。

This said, let’s get started.

这就是说,让我们开始吧。

入门 ( Getting Started )

Whether you are on the business intelligence side or an application developer, most of the fancy coding for data extraction occurs within the “stored procedure”. We are going to create a stored procedure called “SQLShackFiscalFiscalYear”.

无论您是在商业智能方面还是应用程序开发人员,大多数用于数据提取的精美代码都在“存储过程”中进行。 我们将创建一个名为“ SQLShackFiscalFiscalYear”的存储过程。

Opening SQL Server Management Studio we open a new query.

打开SQL Server Management Studio,我们打开一个新查询。

We begin by creating two variables called @beginfiscal and @endfiscal, defined a DATE (see above).

我们首先创建两个定义为DATE的变量@beginfiscal和@endfiscal。

Having declared the two date-related variables, we declare our last two variable @Yearr and @Decider (see above).

声明了两个与日期相关的变量后,我们声明了最后两个变量@Yearr和@Decider(请参见上文)。

To begin, we set @decider to the current month, by converting the current date (utilizing “Getdate()”) to a date format and then stripping the month (see below).

首先,我们将@decider设置为当前月份,方法是将当前日期(使用“ Getdate()”)转换为日期格式,然后剥离月份(请参见下文)。

In a similar fashion we ascertain the current year (see below).

我们以类似的方式确定当年(见下文)。

Now here is where the fun begins. This is the logic that we must construct.

现在,这是乐趣的开始。 这是我们必须构建的逻辑。

Should the ‘month number’ (i.e. the value of @decider) is less than 7 then the beginning of the fiscal year IS NOT the value as shown above BUT rather @yearr-1 or 2014. On the other hand, should @decider be between 7 and 12 then the beginning of the fiscal year is in fact 2015.

如果“月数”(即@decider的值)小于7,则会计年度开始时不是上面显示的值,而是@ yearr-1或2014。另一方面,@ decider应该是在7到12之间,则实际上是2015财年的开始。


set @Yearr    = case when @decider >= 7 then datepart(YEAR,Convert(date,Getdate())) else @Yearr -1 end

The line of code above requires a bit of explanation. If the current month is greater than or equal to 7 then we are in the first half of the fiscal year which is between July 1 and December 31 and as such the beginning date for date extraction must be set to 2015-07-01. Otherwise, the beginning date must be set to 2014-07-01.

上面的代码行需要一些解释。 如果当前月份大于或等于7,则我们处于会计年度的上半年,即7月1日至12月31日之间,因此,必须将日期提取的开始日期设置为2015-07-01。 否则,开始日期必须设置为2014-07-01。


set @Yearr    = case when @decider >= 7 then datepart(YEAR,Convert(date,Getdate())) else @Yearr -1 end
set @Beginfiscal = convert(varchar(4),@Yearr) + '0701'

This is easily achieved utilizing the following line of code.

利用下面的代码行可以轻松实现。


set @Endfiscal   = dateadd(d,-1,dateadd(Year,1,@beginFiscal))

This line of code also requires a bit of explanation as well.
We first add one year to the value of @beginfiscal see below:

这行代码需要一些解释。
我们首先将@beginfiscal的值加一年,如下所示:


dateadd(Year,1,@beginFiscal)

This will set the date to ‘2016-07-01’ (if run in February 2015) which is really the beginning of the NEXT financial year. This is NOT correct. To rectify this we must SUBTRACT one day from this value. We achieve this by enclosing our “DateAdd()” in another “DateAdd()” where we subtract one day (see below).

这会将日期设置为“ 2016-07-01”(如果在2015年2月运行),这实际上是下一财政年度的开始。 这是不正确的 。 要纠正此问题,我们必须从该值中减去一天。 为此,我们将“ DateAdd()”括在另一个“ DateAdd()”中,然后减去一天(请参见下文)。


set @Endfiscal   = dateadd(d,-1,dateadd(Year,1,@beginFiscal)).

An additional feature of this method of setting the end date is that should your fiscal year began March 1 and end on the last day of February, then a “Leap year” is no longer problematic as the last day of February is automatically calculated by the system. Personally, I see this as a definite plus.

这种设置结束日期的方法另一个功能是,如果您的会计年度从3月1日开始,到2月的最后一天结束,那么“ Le年”将不再是问题,因为2月的最后一天是由系统。 我个人认为这是绝对的优势。

Running the query that we have created thus far, we find the following (see below).

运行到目前为止我们创建的查询,我们发现以下内容(请参见下文)。

Playing around a bit and more to prove a point, we arbitrarily change the values of @decider. Let us pretend that we are now in July 2015 (see below).

为了证明这一点,我们不停地更改@decider的值。 让我们假装我们现在是2015年7月(请参阅下文)。

We can clearly see that by setting the month to July that we are into the next fiscal year (see above).

通过将月份设置为下一财政年度的七月,我们可以清楚地看到这一点(请参见上文)。

测试我们新生成的代码 ( Testing our newly generated code )

Having a look at some data within our “DateOnTheFly” table, we find that the lowest date available is September 24th 2014. Sorting the same data in descending order we find that in this case…

查看“ DateOnTheFly”表中的某些数据,我们发现可用的最低日期是2014年9月24 。按降序对相同数据进行排序,我们发现在这种情况下…

the highest date is June 17th 2015 (albeit ahead of our current month “February”). June 2015 data was added for demo purposes only. I believe that the astute reader now understands the concept.

最高日期是2015年6月17 (尽管比我们当月的“ 2月”要早)。 添加了2015年6月的数据仅用于演示目的。 我相信精明的读者现在可以理解这个概念。

So how do we utilize this from a reporting viewpoint?

那么,从报告的角度来看,我们该如何利用呢?

Taking the query that we created (above), we now open up the code listing as shown above.

接受我们创建的查询(上面),现在打开如上所示的代码清单。

We add the following code to our listing. Note that when we extract the month utilizing the DatePart() function, an integer is returned. In adding the code snippet above what I plan to achieve is to create a sort field that would be hidden from the user, however, it would permit the physical month names to be truly sorted from July through June (as opposed to starting in April and ending in September). This is truly important when working with a non-standard fiscal year.

我们将以下代码添加到清单中。 请注意,当我们使用DatePart()函数提取月份时,将返回一个整数。 在我打算实现的目标之上添加代码段是,创建一个对用户隐藏的排序字段,但是,这将允许从7月到6月真正对物理月份名称进行排序(而不是从4月开始, 9月结束)。 在使用非标准会计年度时,这确实很重要。

My two new fields Yearr and MTH may be seen above.

我的两个新字段Yearr和MTH可以在上方看到。

Changing the code slightly and converting the Yearr and MTH fields into Varchar() format, I am able to create a “nifty” field that may be used for accurate data sorting.

稍稍更改代码,然后将Yearr和MTH字段转换为Varchar()格式,就可以创建一个“漂亮”字段,该字段可用于准确的数据排序。

设置日历月份名称 ( Setting the calendar month names )

Once again, I effect a few changes to my code. I convert our current query into a subquery and add another column based upon “case” logic (see below).

再次,我对代码进行了一些更改。 我将当前查询转换为子查询,并根据“大小写”逻辑添加另一列(请参见下文)。

Re-running our query we now find and the calendar month names now appear.

现在,重新运行我们的查询,现在显示日历月名称。

Our final alteration that we shall make is to “total” or sum the market value per YearMth, currency, and fund. The code listing may be found in Addenda 2.

我们要做的最后更改是“合计”或合计YearMth,货币和基金的市场价值。 代码清单可以在附录2中找到。

The results of may be seen in the screen dump above.

的结果可以在上面的屏幕转储中看到。

同时回到Reporting Services的世界。 ( Meanwhile back in the Reporting Services world.. )

A query as such has little aesthetic use. In order to prove out our results, we create a quick and dirty reporting services project (see above).

这样的查询几乎没有美学用途。 为了证明我们的结果,我们创建了一个快速而肮脏的报告服务项目(请参见上文)。

I have described the creation of Reporting Services projects in detail in many of our past “get-togethers”.

我已经在过去的许多“聚会”中详细介绍了如何创建Reporting Services项目。

As always, should you be new to Reporting Services and wish some guidance, then please do have a look my SQL Shack article entitled “Now you see it, now you don’t.

与往常一样,如果您不熟悉Reporting Services并希望获得一些指导,那么请阅读我SQL Shack文章,标题为“现在您看到了,现在您不知道了。

/now-see-now-dont/

/ now-see-now-dont /

As we have done in past exercises, we create a “Shared Data Source” which we call “DatesOnTheFly” (see above).

正如我们在过去的练习中所做的那样,我们创建了一个“共享数据源”,我们将其称为“ DatesOnTheFly”(请参见上文)。

We now create a new report as may be seen above.

如上所示,我们现在创建一个新报告。

We now find ourselves on our report surface.

现在,我们发现自己处于报告表面。

We now create two datasets which will be utilized to populate the query list utilized by two parameters that we shall create in a few seconds.

现在,我们创建两个数据集,这些数据集将用于填充由我们将在几秒钟内创建的两个参数使用的查询列表。

The first dataset will contain a list of the unique funds within our database table.

第一个数据集将包含我们数据库表中唯一资金的列表。

As the reader may see, we pull a distinct copy of each and every fund within the “DateOnTheFly” table.

如读者所见,我们在“ DateOnTheFly”表中提取了每种基金的不同副本。

In a similar manner, we pull distinct copies of the currency codes. Once again, these currency codes will be utilized with the parameters that the end user eventually passes to the stored procedure.

以类似的方式,我们提取货币代码的不同副本。 再一次,这些货币代码将与最终用户最终传递给存储过程的参数一起使用。

配置我们的参数 ( Configuring our parameters )

We first create a “Fund” parameter and as we want our end users to be able to select one or more values, we check the “Allow multiple values” checkbox.

我们首先创建一个“ Fund”参数,并且由于我们希望最终用户能够选择一个或多个值,因此请选中“允许多个值”复选框。

On the available values box, we select “Get values from a query” and select our “Funds” dataset. We click OK to exit the “Report Parameter Properties” dialog box.

在可用值框中,选择“从查询中获取值”,然后选择“基金”数据集。 我们单击“确定”退出“报表参数属性”对话框。

In a similar fashion we create our “CurrCode” Parameter (see below).

我们以类似的方式创建“ CurrCode”参数(请参见下文)。

Our next task is to construct a dataset to contain our financial data.

我们的下一个任务是构建一个包含我们的财务数据的数据集。

Having converted the query in Addenda 2 to a stored procedure (see Addenda3), we utilize this stored procedure to pull our data.

在将Addenda 2中的查询转换为存储过程(请参阅Addenda3)之后,我们利用此存储过程提取数据。

Having configured our dataset to utilize the stored procedure “SQLShackFiscalFiscalYear”, we must now configure the two parameters that are passed to the stored procedure (in order to populate the dataset at runtime). The issue is that we set the parameter to accept multiple values to be sent to the stored procedure. This required concatenating the individual values into a string. This is achieved in by utilizing the “JOIN” statement as may be seen above. A code snippet may be seen below.

配置数据集以利用存储过程“ SQLShackFiscalFiscalYear”之后,我们现在必须配置传递给存储过程的两个参数(以便在运行时填充数据集)。 问题是我们将参数设置为接受要发送到存储过程的多个值 。 这需要将各个值连接成一个字符串。 如上所示,这是通过利用“ JOIN”语句实现的。 可以在下面看到一个代码片段。


=JOIN(Parameters!CurrCode.Value,",")

The “Funds” parameter is set up in a similar fashion (see above).

“基金”参数的设置方式与此类似(请参见上文)。

与其他所有内容一样,代码也会更改! ( As with everything else, code changes!! )

In order for our store procedure (see Addenda 3) to correctly handle Reporting Services multiple selects we need to add two small additional code snippets.

为了使我们的存储过程(请参阅附录3)正确处理Reporting Services的多项选择,我们需要添加两个小的附加代码段。

Fund

基金


-- Split the Fund stringdeclare @Comma CHAR(1)
declare @Fund table
(
fundid varchar(8) NOT NULL
)  Set @Comma = ','BEGINDECLARE @Position INTDECLARE @Substringg VARCHAR(8000)SELECT @Position =1IF (LEN(@fundid)<1) OR @fundid IS NULL RETURNWHILE @Position!=0BEGINSET @Position=CHARINDEX(@Comma,@fundid)IF @Position<>0SET @Substringg=LEFT(@fundid,@Position-1)ELSESET @Substringg=@fundidIF(LEN(@Substringg)>0)INSERT INTO @Fund(fundid) VALUES(RTRIM(LTRIM(@Substringg)))SET @fundid=RIGHT(@fundid,LEN(@fundid)-@Position)IF LEN(@fundid)=0 BREAKEND select fundid as [fundid] Into #fund from @fundEND

CurrencyCode

货币代码


-- Split the Currency Code string
--If we wish to use @Position again as a marker we need to re-initialize it
Set @Position = 0
Set @Substringg = ''
declare @Currency1 table
(
Currency varchar(8) NOT NULL
)  Set @Comma = ','BEGIN--DECLARE @Position INT--DECLARE @Substringg VARCHAR(8000)SELECT @Position =1IF (LEN(@currency)<1) OR @currency IS NULL RETURNWHILE @Position!=0BEGINSET @Position=CHARINDEX(@Comma,@currency)IF @Position<>0SET @Substringg=LEFT(@currency,@Position-1)ELSESET @Substringg=@currencyIF(LEN(@Substringg)>0)INSERT INTO @currency1 (currency) VALUES(RTRIM(LTRIM(@Substringg)))SET @currency =RIGHT(@currency,LEN(@currency)-@Position)IF LEN(@currency)=0 BREAKEND select currency as [currency] Into #currency from @currency1END

When we run our query (once again), this time including our list of funds, passed by our report, the stripping code adds each code to a table variable and when complete places the values into temporary tables. We can see the results of running the query above. Note the currency codes in the “first select” and the main results in the “second select”. NOTE that no filtering has been put in place. We are going to do this now.

当我们运行查询(再次一次)时,这次包括我们的报告传递的资金清单,剥离代码将每个代码添加到表变量中,完成后将值放入临时表中。 我们可以在上面看到运行查询的结果。 注意“第一选择”中的货币代码,而“第二选择”中的主要结果。 请注意,尚未进行任何过滤。 我们现在要这样做。

In the screenshot above, the astute reader will note that I have utilized inner joins as a filtering mechanism as opposed to saying “where fund in (‘PAT2’, ‘MIT1’) etc. There is a reason behind my madness. It is left up to the reader to postulate why. As a hint.. what will happen should the user decide to choose more than 1000 funds OR more than 1000 currency codes (if this was possible)?

在上面的屏幕截图中, 精明的读者会注意到,我已经将内部联接用作过滤机制 ,而不是说“资金在何处('PAT2','MIT1')等。这是我疯狂的原因。 由读者来说明原因。 作为提示..用户应该选择超过1000种资金还是超过1000种货币代码(如果可能的话)?

同时回到我们的设计屏幕 ( Meanwhile back on our design screen )

We add a chart to our drawing surface (see above).

我们将图表添加到绘图表面(请参见上文)。

We configure our chart as follows. For the values box of the chart data, we set this to “Market Value”. For the “Category Groups”, we set this to YearMth as the sorting field. This field as discussed is used as a sort field and is HIDDEN to the user.

我们按如下方式配置图表。 对于图表数据的值框,我们将其设置为“市场价值”。 对于“类别组”,我们将此设置为YearMth作为排序字段。 所讨论的该字段用作排序字段,并且对用户隐藏。

To hide this field, we change its “Label” to nothing (see above).

为了隐藏该字段,我们将其“标签”更改为空(请参见上文)。

We also add the “Monthee” field which if we remember correctly contains the calendar month name.

我们还会添加“ Monthee”字段,如果我们没有记错的话,其中包含日历月份名称。

Finally, we set the “Series Group” to the currency code field “FND_TOT_CURR_CD” (see above).

最后,我们将“系列组”设置为货币代码字段“ FND_TOT_CURR_CD”(请参见上文)。

让我们旋转一下 ( Let us give it a whirl )

Putting my report into “Preview” mode, I am able to select the parameters that I wish (see above). I now click “View Report”.

将报告置于“预览”模式,可以选择所需的参数(请参见上文)。 我现在单击“查看报告”。

Our final report may be seen above. Note that there are in fact two currencies shown for each month albeit the CAD values are very small.

我们的最终报告可能在上方。 请注意,尽管CAD值很小,但实际上每个月显示两种货币。

结论 ( Conclusions )

Thus we come to the end of another “get together”. We have seen that while most reporting is “Date” dependant, oft times it is not necessary to specify a start and end date as this may be calculated from the system date.

因此,我们走到了另一个“聚在一起”的结尾。 我们已经看到,尽管大多数报告取决于“日期”,但通常不必指定开始和结束日期,因为它可以从系统日期计算得出。

We have also seen how this technique may be utilized with stored procedures and Reporting Services alike.

我们还看到了如何将该技术与存储过程和Reporting Services一起使用。

Do try to utilize this technique in your day to day work. It will bear fruit!

尝试在日常工作中利用这种技术。 会结出果实的!

In the interim, happy programming!

在此期间,编程愉快!

附录1 ( Addenda 1 )


use [SQLShackFinancial]
go
--CREATE procedure [dbo].[SQLShackFiscalFiscalYear]
--as
declare @beginFiscal date
declare @endFiscal date
declare @Yearr varchar(4)
declare @decider int
-- The guts of the code
set @decider = datepart(Month,convert(date,getdate()))
set @Yearr   = datepart(YEAR,Convert(date,Getdate()))
set @Decider = 7
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], @decider

附录2 ( Addenda 2 )


use [SQLShackFinancial]
go
--CREATE procedure [dbo].[SQLShackFiscalFiscalYear]
--as
declare @beginFiscal date
declare @endFiscal date
declare @Yearr varchar(4)
declare @decider int
-- The guts of the code
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 fund_ID, FND_TOT_CURR_CD, sum(MKT_VAL_TOT_AMT) as [Market Value] , YearMth,case when right(YearMth,2) = '01' then 'Jan'when right(YearMth,2) = '02' then 'Feb'when right(YearMth,2) = '03' then 'Mar'when right(YearMth,2) = '04' then 'Apr'when right(YearMth,2) = '05' then 'May'when right(YearMth,2) = '06' then 'Jun'when right(YearMth,2) = '07' then 'Jul'when right(YearMth,2) = '08' then 'Aug'when right(YearMth,2) = '09' then 'Sep'when right(YearMth,2) = '10' then 'Oct'when right(YearMth,2) = '11' then 'Nov'when right(YearMth,2) = '12' then 'Dec' else '99' end as Montheefrom (select FUND_ID, CAL_DT, FND_TOT_TYP_CD, FND_TOT_CURR_CD, MKT_VAL_TOT_AMT
,convert(varchar(4),datepart(year,Convert(date,Cal_dt)))  +
Convert(varchar(2),case when len(datepart(month,Convert(date,Cal_dt))) = 1 then
'0' + convert(varchar(2),datepart(month,Convert(date,Cal_dt)))
else  convert(varchar(2),datepart(month,Convert(date,Cal_dt))) end)  as YearMth
from [dbo].[DateOnTheFly]
where cal_dt between @beginFiscal and @endFiscal
)a
Group by
FUND_ID,  FND_TOT_TYP_CD, FND_TOT_CURR_CD,YearMth,case when right(YearMth,2) = '01' then 'Jan'when right(YearMth,2) = '02' then 'Feb'when right(YearMth,2) = '03' then 'Mar'when right(YearMth,2) = '04' then 'Apr'when right(YearMth,2) = '05' then 'May'when right(YearMth,2) = '06' then 'Jun'when right(YearMth,2) = '07' then 'Jul'when right(YearMth,2) = '08' then 'Aug'when right(YearMth,2) = '09' then 'Sep'when right(YearMth,2) = '10' then 'Oct'when right(YearMth,2) = '11' then 'Nov'when right(YearMth,2) = '12' then 'Dec' else '99' end order by YearMth desc

附录3 ( Addenda 3 )


use [SQLShackFinancial]
go
alter procedure [dbo].[SQLShackFiscalFiscalYear]
(
@currency varchar(2000),
@fundid varchar(2000)
)
as
declare @beginFiscal date
declare @endFiscal date
declare @Yearr varchar(4)
declare @decider int
-- The guts of the code
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 fund_ID, FND_TOT_CURR_CD, sum(MKT_VAL_TOT_AMT) as [Market Value] , YearMth,case when right(YearMth,2) = '01' then 'Jan'when right(YearMth,2) = '02' then 'Feb'when right(YearMth,2) = '03' then 'Mar'when right(YearMth,2) = '04' then 'Apr'when right(YearMth,2) = '05' then 'May'when right(YearMth,2) = '06' then 'Jun'when right(YearMth,2) = '07' then 'Jul'when right(YearMth,2) = '08' then 'Aug'when right(YearMth,2) = '09' then 'Sep'when right(YearMth,2) = '10' then 'Oct'when right(YearMth,2) = '11' then 'Nov'when right(YearMth,2) = '12' then 'Dec' else '99' end as Montheefrom (select FUND_ID, CAL_DT, FND_TOT_TYP_CD, FND_TOT_CURR_CD, MKT_VAL_TOT_AMT
,convert(varchar(4),datepart(year,Convert(date,Cal_dt)))  +
Convert(varchar(2),case when len(datepart(month,Convert(date,Cal_dt))) = 1 then
'0' + convert(varchar(2),datepart(month,Convert(date,Cal_dt)))
else  convert(varchar(2),datepart(month,Convert(date,Cal_dt))) end)  as YearMth
from [dbo].[DateOnTheFly]
where cal_dt between @beginFiscal and @endFiscal
)a
Group by
FUND_ID,  FND_TOT_TYP_CD, FND_TOT_CURR_CD,YearMth,case when right(YearMth,2) = '01' then 'Jan'when right(YearMth,2) = '02' then 'Feb'when right(YearMth,2) = '03' then 'Mar'when right(YearMth,2) = '04' then 'Apr'when right(YearMth,2) = '05' then 'May'when right(YearMth,2) = '06' then 'Jun'when right(YearMth,2) = '07' then 'Jul'when right(YearMth,2) = '08' then 'Aug'when right(YearMth,2) = '09' then 'Sep'when right(YearMth,2) = '10' then 'Oct'when right(YearMth,2) = '11' then 'Nov'when right(YearMth,2) = '12' then 'Dec' else '99' end order by YearMth desc

附录4 ( Addenda 4 )


use [SQLShackFinancial]
go
IF OBJECT_ID(N'tempdb..#Fund') IS NOT NULL
BEGINDROP TABLE #Fund
END
IF OBJECT_ID(N'tempdb..#Currency') IS NOT NULL
BEGINDROP TABLE #Currency
END
Go
--alter procedure [dbo].[SQLShackFiscalFiscalYear]
--(
--@currency varchar(2000),
--@fundid varchar(2000)
--)
--asDeclare @currency varchar(2000)
Declare @fundid varchar(2000)
set @Currency = 'USD, CAD'
Set @Fundid = 'Pat2, FDR1'
declare @beginFiscal date
declare @endFiscal date
declare @Yearr varchar(4)
declare @decider int
-- The guts of the code
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))declare @Comma CHAR(1)
declare @Fund table
(
fundid varchar(8) NOT NULL
)  Set @Comma = ','BEGINDECLARE @Position INTDECLARE @Substringg VARCHAR(8000)SELECT @Position =1IF (LEN(@fundid)<1) OR @fundid IS NULL RETURNWHILE @Position!=0BEGINSET @Position=CHARINDEX(@Comma,@fundid)IF @Position<>0SET @Substringg=LEFT(@fundid,@Position-1)ELSESET @Substringg=@fundidIF(LEN(@Substringg)>0)INSERT INTO @Fund(fundid) VALUES(RTRIM(LTRIM(@Substringg)))SET @fundid=RIGHT(@fundid,LEN(@fundid)-@Position)IF LEN(@fundid)=0 BREAKEND select fundid as [fundid] Into #fund from @fundENDSet @Position = 0Set @Substringg = ''
declare @Currency1 table
(
Currency varchar(8) NOT NULL
)  Set @Comma = ','BEGIN--DECLARE @Position INT--DECLARE @Substringg VARCHAR(8000)SELECT @Position =1IF (LEN(@currency)<1) OR @currency IS NULL RETURNWHILE @Position!=0BEGINSET @Position=CHARINDEX(@Comma,@currency)IF @Position<>0SET @Substringg=LEFT(@currency,@Position-1)ELSESET @Substringg=@currencyIF(LEN(@Substringg)>0)INSERT INTO @currency1 (currency) VALUES(RTRIM(LTRIM(@Substringg)))SET @currency =RIGHT(@currency,LEN(@currency)-@Position)IF LEN(@currency)=0 BREAKEND select currency as [currency] Into #currency from @currency1ENDSelect fund_ID, FND_TOT_CURR_CD, sum(MKT_VAL_TOT_AMT) as [Market Value] , YearMth,case when right(YearMth,2) = '01' then 'Jan'when right(YearMth,2) = '02' then 'Feb'when right(YearMth,2) = '03' then 'Mar'when right(YearMth,2) = '04' then 'Apr'when right(YearMth,2) = '05' then 'May'when right(YearMth,2) = '06' then 'Jun'when right(YearMth,2) = '07' then 'Jul'when right(YearMth,2) = '08' then 'Aug'when right(YearMth,2) = '09' then 'Sep'when right(YearMth,2) = '10' then 'Oct'when right(YearMth,2) = '11' then 'Nov'when right(YearMth,2) = '12' then 'Dec' else '99' end as Montheefrom (select FUND_ID, CAL_DT, FND_TOT_TYP_CD, FND_TOT_CURR_CD, MKT_VAL_TOT_AMT
,convert(varchar(4),datepart(year,Convert(date,Cal_dt)))  +
Convert(varchar(2),case when len(datepart(month,Convert(date,Cal_dt))) = 1 then
'0' + convert(varchar(2),datepart(month,Convert(date,Cal_dt)))
else  convert(varchar(2),datepart(month,Convert(date,Cal_dt))) end)  as YearMth
from [dbo].[DateOnTheFly]  DOTFinner join #Fund fund
on DOTF.Fund_ID = fund.fundidInner join #Currency currency
on currency.currency = DOTF.FND_TOT_CURR_CDwhere cal_dt between @beginFiscal and @endFiscal
)a
Group by
FUND_ID,  FND_TOT_TYP_CD, FND_TOT_CURR_CD,YearMth,case when right(YearMth,2) = '01' then 'Jan'when right(YearMth,2) = '02' then 'Feb'when right(YearMth,2) = '03' then 'Mar'when right(YearMth,2) = '04' then 'Apr'when right(YearMth,2) = '05' then 'May'when right(YearMth,2) = '06' then 'Jun'when right(YearMth,2) = '07' then 'Jul'when right(YearMth,2) = '08' then 'Aug'when right(YearMth,2) = '09' then 'Sep'when right(YearMth,2) = '10' then 'Oct'when right(YearMth,2) = '11' then 'Nov'when right(YearMth,2) = '12' then 'Dec' else '99' end order by YearMth desc

翻译自: https://www.sqlshack.com/reporting-sql-server-create-chart-based-on-data-extracted-for-given-date-range/

对于数据给定范围sql取数

对于数据给定范围sql取数_SQL Server中的报表–根据给定日期范围内提取的数据创建图表相关推荐

  1. sql 实现决策树_SQL Server中的Microsoft决策树

    sql 实现决策树 Decision trees, one of the very popular data mining algorithm which is the next topic in o ...

  2. oracle 动态sql列转行_SQL Server中动态列转行

    http://www.cnblogs.com/gaizai/p/3753296.html 一.本文所涉及的内容(Contents) 三.实现代码(SQL Codes) (一) 首先我们先创建一个测试表 ...

  3. sql limit 子句_SQL Server中的FOR XML PATH子句

    sql limit 子句 As SQL professionals, we often have to deal with XML data in our databases. This articl ...

  4. sql语句截断_SQL Server中SQL截断和SQL删除语句之间的区别

    sql语句截断 We get the requirement to remove the data from the relational SQL table. We can use both SQL ...

  5. sql判断基数_SQL Server中的基数估计框架版本控制

    sql判断基数 This is a small post about how you may control the cardinality estimator version and determi ...

  6. server sql 本月最后一天_SQL SERVER中求上月、本月和下月的第一天和最后一天 DATEADD DATEDIFF...

    1.上月的第一天 SELECT CONVERT(CHAR(10),DATEADD(month,-1,DATEADD(dd,-DAY(GETDATE())+1,GETDATE())),111) 2.上月 ...

  7. BI 不是可以拖拉拽取数吗?为什么还要 SQL 取数 ?

    BI 工具不是可以直接拖拉拽取数吗 ?为什么还要写 SQL 取数 ? 这是很多初次接触商业智能 BI 的朋友会提到的一个问题,因为在他们接触到一些 BI 市场或者产品宣传的时候,很多人就是这么来介绍 ...

  8. 计算机组成原理学习笔记————计算机指令,MIPS指令集,存储器操作数,数据传送指令,取数存数指令

    计算机语言 现在计算机编程常用的语言是C,C++,Java等高级语言,但计算机第层是将高级编程语言的代码编译成二进制代码形式的指令才能执行.所以计算机语言中的基本单词是二进制形式的指令,一台计算机的全 ...

  9. mysql查询每个id的前10条数据_解决 MySQL 比如我要拉取一个消息表中用户id为1的前10条最新数据...

    我们都知道,各种主流的社交应用或者阅读应用,基本都有列表类视图,并且都有滑到底部加载更多这一功能, 对应后端就是分页拉取数据. 好处不言而喻,一般来说,这些数据项都是按时间倒序排列的,用户只关心最新的 ...

最新文章

  1. spring 获取配置文件的值
  2. 通用Makefile实现
  3. 耗时1周!精选22G超超超适合产品经理的《数据分析》学习资源,抓紧保存!限时2天删除~...
  4. java skip函数_【Java必修课】图说Stream中的skip()和limit()方法及组合使用
  5. 错误记录(五)Error creating bean with name 'sessionFactory' defined in file
  6. c语言可变参数 printf,c语言 使用可变参数列表实现printf(my_printf)
  7. 大数据之-Hadoop之HDFS的API操作_文件夹_以及文件删除案例---大数据之hadoop工作笔记0059
  8. 《Velocity 模板使用指南》中文版[转]
  9. Thinkphp 生成数据表字段缓存
  10. U盘无法格式化的解决方法
  11. Sublime快捷键大全
  12. 手把手教你从AVI转RMVB的压制全程(转)
  13. oracle静默安装报错,Oracle静默安装说明
  14. pdf裁边app_PDF切边裁剪(paper for kindle)下载_PDF切边裁剪(paper for kindle)官方下载-太平洋下载中心...
  15. pvs-stdio ue4_PlatformIO中的PVS-Studio集成
  16. 遍历同辈节电的方法_家庭节水节电的24个好方法
  17. PeopleSoft 配置文件
  18. 汇编语言_一些寄存器与寻址方式
  19. python之小说下载器version3.0
  20. python url转码_Python如何实现转换URL详解

热门文章

  1. HTML li标签排列有空白间隙
  2. Fragment与Activity之间的相互通信
  3. CSS定位 position
  4. 基于c#的windows基础设计(学习日记1)【关于异或运算】
  5. Vsphere初试——基本安装
  6. SignalR循序渐进(三)简易的集群通讯组件
  7. 上海雄联机械配件有限公司
  8. 文件包含漏洞对公司测试
  9. JS:ES6-4 简化对象与箭头函数
  10. JS:ES6-3 解构赋值与模板字符串