在T-SQL中,如何根据今天的条件获取属于上个月的记录?

时间:2012-11-13 19:09:47

标签: sql-server tsql

如果今天的日期成分小于或等于19,我需要从上一个月的第20个月到未来的记录。例如:

dbo.Invoices

Date        InvoiceNumber
10/20/2012  x
11/13/2012  y
11/20/2012  z
12/19/2012  aa
12/21/2012  bb

今天(11月13日),我需要x,y,z,aa,bb 11月20日,我需要z,aa,bb。
12月19日,我需要z,aa,bb。
12月21日,我需要bb。

这是我到目前为止所做的:

SELECT [omitted]
,CASE
    WHEN DAY(GETDATE()) <= 19 THEN

FROM QB_INVOICES_HEADER a
INNER JOIN CI_INVOICEADJS b
ON a.InvoiceNumber = b.InvoiceNumber
WHERE DATEDIFF(day, a.InvoiceDt, b.EffectiveCheckingDt) <= 60
ORDER BY b.EffectiveCheckingDt ASC

3 个答案:

答案 0 :(得分:1)

您需要使用DATEPART(DAY, [YOUR DATE COLUMN])来判断它是哪个日期。

答案 1 :(得分:1)

下面的代码解决了您的任务。我使用表变量@invoices而不是您的dbo.invoices

DECLARE @invoices TABLE ([date] DATE, invoiceNumber varchar(255));

INSERT INTO @invoices VALUES
    ('10/20/2012', 'x'),
    ('11/13/2012', 'y'),
    ('11/20/2012', 'z'),
    ('12/19/2012', 'aa'),
    ('12/21/2012', 'bb');

DECLARE @StartDate DATE;
DECLARE @today DATE ;

SET @today = '11/13/2012';
--SET @today = '11/20/2012';
--SET @today = '12/19/2012';
--SET @today = '12/21/2012';

IF DAY(@today) <= 19 BEGIN
    SET @startDate = DATETIMEFROMPARTS(YEAR(@today), MONTH(@today) - 1, 20,0,0,0.0,0);
END
ELSE BEGIN
    SET @startDate = @today
END

SELECT [date], invoiceNumber
FROM @invoices
WHERE [date] >= @StartDate

答案 2 :(得分:1)

只是SQL查询:

<强> SQLFIDDLEExample

SELECT
InvoiceNumber
FROM Invoices
WHERE Date >= CASE WHEN DAY(GETDATE())<=19 
                    THEN CAST(MONTH(DATEADD (mm , -1 , GETDATE() )) as varchar(2))+
                         '/20/'+CAST(YEAR(DATEADD (mm , -1 , GETDATE() )) as varchar(4))
                    ELSE CONVERT(VARCHAR(10), GETDATE(), 101) 
              END

如果你想要不同的日期,只需将GETDATE()替换为'10 / 19/2012'

SELECT
InvoiceNumber
FROM Invoices
WHERE Date >= CASE WHEN DAY('12/19/2012')<=19 
                    THEN CAST(MONTH(DATEADD (mm , -1 , '12/19/2012' )) as varchar(2))+
                         '/20/'+CAST(YEAR(DATEADD (mm , -1 , '12/19/2012' )) as varchar(4))
                    ELSE CONVERT(VARCHAR(10), '12/19/2012', 101) 
              END

第二次查询的结果:

| INVOICENUMBER |
-----------------
|             z |
|            aa |
|            bb |