T-SQL查询比较日期并查找列条目是否存在一个月

时间:2016-07-27 08:16:12

标签: sql-server tsql

我有一个名为“Statement Date”和“Account Number”的两列。对于某些帐号,语句每月上传一次,每季度一些,每年一些,上传这些语句的日期保存在“声明日期”

我想检查是否上传了特定的语句。 例如 - “帐号”-2345426576“陈述日期”2016年5月30日,我必须检查上个月(2016年4月30日)和下个月(2016年6月30日)是否有入境。如果没有条目,则该月份应该返回缺失。

如果要比较不同表的日期,然后查找是否缺少某个陈述。如果t1.date> t2.date则检查t1.date是多少个月。如果t1.date也一样

2 个答案:

答案 0 :(得分:0)

为此创建一个函数:

CREATE FUNCTION [dbo].[IsUploaded]
(
       @AccountNo int,
       @Date datetime
)
RETURNS bit
AS
BEGIN
    DECLARE @MonthStart datetime
    DECLARE @NextMonthStart datetime


    -- current month 
   SET @MonthStart = DATEADD(month, DATEDIFF(month, 0, @Date), 0)
   SET @NextMonthStart = DATEADD(month, 1, @MonthStart)

   IF EXISTS (SELECT 1 From UploadedStatememtsTable WHERE UploadDate >= @MonthStart AND UploadDate < @NextMonthStart AND AccountNo = @AccountNo) 
      RETURN 1

   -- next month
   SET @MonthStart = @NextMonthStart
   SET @NextMonthStart = DATEADD(month, 1, @MonthStart)

   IF EXISTS (SELECT 1 From UploadedStatememtsTable WHERE UploadDate >= @MonthStart AND UploadDate < @NextMonthStart AND AccountNo = @AccountNo) 
      RETURN 1

   -- previous month
   SET @MonthStart = DATEADD(month, -2, @MonthStart)
   SET @NextMonthStart = DATEADD(month, 1, @MonthStart)

   IF EXISTS (SELECT 1 From UploadedStatememtsTable WHERE UploadDate >= @MonthStart AND UploadDate < @NextMonthStart AND AccountNo = @AccountNo) 
      RETURN 1

   RETURN 0

END

答案 1 :(得分:0)

试试这个

SELECT
    T.accountnumber,
    T.statementdate,    
    CASE
      WHEN 
        EXISTS
        (
            SELECT TOP 1 1 FROM Tbl tmp
            WHERE
                tmp.accountnumber = T.accountnumber AND
                tmp.statementdate =  DATEADD(mm, 1, T.statementdate) -- Next month
        ) AND
        EXISTS
        (
            SELECT TOP 1 1 FROM Tbl tmp
            WHERE
                tmp.accountnumber = T.accountnumber AND                 
                tmp.statementdate =  DATEADD(mm, -1, T.statementdate)-- Priv month
        )   
      THEN 'There is entry'
      ELSE 'Missing' END 
FROM
    Tbl T