我的项目中有一个存储过程,它返回从今天到即将到来的49天的金额总和。我想以一种将2014-01-01作为开始日期并从该日期返回数据的方式修改此存储过程。例如,
Total_amount StartDate EndDate
50000 2014-01-01 2014-02-18
40000 2014-02-19 2014-04-08
这是我的存储过程,
USE [myDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[my_sp]
AS
BEGIN
select sum(amount) as Total_amount,
getdate() as StartDate,
dateadd(dd, 48, dateadd(dd, -(datepart(dw, getdate())-2), getdate())) as EndDate
from my_table
where Col_Date > dateadd(dd, -1, getdate())
and Col_Date < dateadd(dd, 49, dateadd(dd, -(datepart(dw, getdate())-2), getdate()))
END
任何帮助都将不胜感激。
感谢。
答案 0 :(得分:0)
getdate()函数返回今天的日期。因此,您可以将其更改为例如&#39; 2014-01-01&#39;。
答案 1 :(得分:0)
如果我理解正确,您想知道如何在存储过程中添加日期参数。然后,您希望在过程中使用提供的日期而不是今天的日期。
这不难做到:
ALTER PROCEDURE [dbo].[my_sp] (@startdate datetime)
AS
BEGIN
select sum(amount) as Total_amount,@startdate as StartDate,dateadd(dd,48,dateadd(dd,-(datepart(dw,@startdate)-2),@startdate)) as EndDate
from my_table
where Col_Date > dateadd(dd,-1,@startdate)
and Col_Date < dateadd(dd,49,dateadd(dd,-(datepart(dw,@startdate)-2),@startdate))
END
答案 2 :(得分:0)
据我所知,必须是这样的:
ALTER PROCEDURE [dbo].[my_sp]
AS
BEGIN
select sum(amount) as Total_amount,
getdate() as StartDate,
dateadd(dd, 48, dateadd(dd, -(datepart(dw, getdate())-2), getdate())) as EndDate
from my_table
where Col_Date > '2014-01-01'
END
答案 3 :(得分:0)
这是基于我更好地理解你的目标的另一种方法。我使用公用表表达式来设置一个表格,提供49天的桶和#39;然后加入该列表以总结相应的总数。
ALTER PROCEDURE [dbo].[my_sp] (@startdate datetime)
AS
BEGIN
-------------------------
-- Set up a table that lists off 49 day periods starting from @startDate
-------------------------
DECLARE @endDate DATETIME = getdate();
WITH [dates] ([startDate], [maxDate_Excluded]) AS
(SELECT
@startDate AS [startDate]
,DATEADD(d, 49, @startDate) AS [maxDate_Excluded]
UNION ALL
SELECT
DATEADD(d, 49, [startDate]) AS [startDate]
,DATEADD(d, 98, [startDate]) AS [maxDate_Excluded]
FROM [dates]
WHERE [startDate] < @endDate
)
, dateFrame AS
(
SELECT
[startDate]
,[maxDate_Excluded]
FROM [dates]
)
-------------------------
-- JOIN and sum.
-------------------------
SELECT
[startDate]
, dateadd(d, -1, [maxDate_Exclued]) as endingDate
, Sum(amount) as total_amount
FROM
dateFrame df
left join my_table mt
on mt.col_date >= df.startDate
and mt.col_date < df.maxDate_Excluded
GROUP BY
[startDate]
,[maxDate_Excluded]
ORDER by
[startDate]
END