如何编写查询以提取给定日期每一年的数据

时间:2019-01-15 21:25:54

标签: sql sql-server ssms

我有一个查询,其中需要提取给定日期的Claims数据并返回给定日期之前每年的数据,例如

我今天有个要求:1/15/2019

我希望能够在一个通用查询中提取所有其他年份,因为这将是一个存储过程。

这将使我查看过去几年中在给定日期是否有索赔。

如果我要创建变量或案例陈述,那么我可以分别执行1年,2年,3年,但是有没有一种方法可以更简单地完成所有这些?

这是一年前的代码:

SELECT * FROM tblClaim c
WHERE c.IncidentDate = DATEadd(year, -1, CAST(FLOOR( CAST(GETDATE() AS FLOAT)) AS DATETIME)) AND c.StatusID = 2

3 个答案:

答案 0 :(得分:2)

嗯?仅使用日期部分应该会更容易:

(echo $! | php test.php | tee log.txt &2>&1 /dev/null) &

两个注意事项:

  • 当心2月29日。
  • 这将不使用索引。

答案 1 :(得分:0)

因此,如果您想将其作为存储过程进行处理,这就是我要处理的leap年。也许有一种更简单的方法,但我想不到。如果您打算使用SSRS,也可以将我的输入参数更改为灵活的日期。

我创建了一个模拟表:

public void CloseAllDialogs(int threadId) {
    EnumThreadWndProc callback = new EnumThreadWndProc(checkIfHWNDPointsToWindowsDialog);
    EnumThreadWindows(threadId, callback, IntPtr.Zero);
    GC.KeepAlive(callback);
}

private bool checkIfHWNDPointsToWindowsDialog(IntPtr hWnd, IntPtr lp) {
    StringBuilder sb = new StringBuilder(260);
    GetClassName(hWnd, sb, sb.Capacity);
    if (sb.ToString() == "#32770") {
        SendMessage(hWnd, 0x0010, IntPtr.Zero, IntPtr.Zero);
    }
    return true;
}

private delegate bool EnumThreadWndProc(IntPtr hWnd, IntPtr lp);

[DllImport("user32.dll", SetLastError = true)]
private static extern bool EnumThreadWindows(int tid, EnumThreadWndProc callback, IntPtr lp);

[DllImport("kernel32.dll", SetLastError = true)]
private static extern int GetCurrentThreadId();

[DllImport("user32.dll", SetLastError = true)]
private static extern int GetClassName(IntPtr hWnd, StringBuilder buffer, int buflen);

[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);

然后我创建了一个proc(调整您需要相应显示的变量):

CREATE TABLE #tblClaim (statusid INT, incidentdate DATE)
INSERT INTO #tblClaim (statusid, incidentdate)
VALUES (1,'2019-01-15'),(2,'2019-01-15'),(1,'2018-01-15'),(2,'2018-01-15'),
       (1,'2017-01-15'),(2,'2016-01-15'),(1,'2012-02-29'),(2,'2012-02-29'),
       (1,'2016-02-29'),(2,'2016-02-29'),(1,'2008-02-29'),(2,'2008-02-29'),
       (1,'2012-02-28'),(2,'2012-02-28'),(1,'2016-03-01'),(2,'2016-03-01'),
       (1,'2008-03-01'),(2,'2008-02-28');

Le年返回以下结果:

enter image description here

今天的日期返回:

enter image description here

答案 2 :(得分:0)

此查询将提供3年数据

select [date] from TableName where (year([date]) = year(getdate())-1
or year([date]) = year(getdate())-2
or year([date]) = year(getdate())-3)