【问题标题】:Array like function for a statement语句的类似函数的数组
【发布时间】:2019-11-21 11:12:42
【问题描述】:

我有一个语句返回一个日期的单个数字。我想要做的是能够跨日期范围执行语句并获取每个日期的值。

select dbo.GetItemMTDIssues(inmastx.fac, inmastx.fpartno, inmastx.frev, '6-01-2019') 
as MTDiss from inmastx where fpartno='ANF-10-6313-102'

这就是我在当前声明中获得的单个日期的结果。 2019 年 6 月 1 日

|MTDiss|   
  600

这是我在 6-01-2019 - 6-05-2019 等日期范围内想要的预期结果

|MTDiss|   
  600   
  450   
  375   
  700   
  300

如果有帮助,还包括该功能。

CREATE FUNCTION [dbo].[GetItemMTDIssues]
    (@fac char(20), @partno char(25), @rev char(3), @currentdate datetime)
    returns numeric (15,5)
    as

    begin
        declare @returnval as numeric (15,5)

        set @returnval =
        isnull(
        (select sum(fQty) 
                from intran 
                where ftype = 'I'
                and month(fdate) = month(@currentdate)
                and year(fdate) = year(@currentdate)
                and fac = @fac
                and fpartno = @partno
                and fcpartrev = @rev)
        ,0.0) * -1

        return @returnval
    end

【问题讨论】:

  • 添加信息以获得更好的想法@GordonLinoff

标签: sql tsql sql-server-2008-r2


【解决方案1】:

您需要首先创建范围,下面的 t-sql 将执行此操作。

declare @startDate datetime='6-01-2019'
declare @endDate datetime='6-05-2019'

;with DateRange as (
select @startDate [date]
union all
select DATEADD(day,1,[date]) [date] from DateRange where [date]<@endDate
)
select * from DateRange

我们可以对其进行测试并查看结果以确认这是我们想要的范围。 注意:如果您需要按月或按天数跳转,您只需更改 DATEADD 中的代码即可。

现在我们需要更新您的函数以获取范围的开始和结束,并让它使用所有范围日期,我认为以下内容会有所帮助:-

CREATE FUNCTION [GetItemMTDIssuesRange]
(   
@fac char(20), @partno char(25), @rev char(3), @startDateRange datetime, @EndDateRange datetime
)
RETURNS TABLE 
AS
RETURN 
(
    with DateRange as (
    select @startDateRange [date]
    union all
    select DATEADD(day,1,[date]) [date] from DateRange where [date]<@EndDateRange
    )
    --select * from DateRange
    select (isnull(sum(fQty),0.0) * -1) MTDiss
                    from intran 
                    inner join DateRange on year(fdate) = year(DateRange.[date]) and month(fdate) = month(DateRange.[date]) 
                    where ftype = 'I'
                    and fac = @fac
                    and fpartno = @partno
                    and fcpartrev = @rev
                    group by DateRange.[date]
)
GO

请检查一下。

如果您不想更改功能,以下内容也可能有所帮助:-

declare @startDate datetime='6-01-2019'
declare @endDate datetime='6-05-2019'

;with DateRange as (
select @startDate [date]
union all
select DATEADD(day,1,[date]) [date] from DateRange where [date]<@endDate
)
select dbo.GetItemMTDIssues(inmastx.fac, inmastx.fpartno, inmastx.frev, DateRange.[date]) 
as MTDiss from inmastx,DateRange
 where fpartno='ANF-10-6313-102'

【讨论】:

    猜你喜欢
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    • 2019-06-19
    相关资源
    最近更新 更多