English 中文(简体)
打印日期范围内的记录,如果不在日期范围内,则打印最后一条记录
原标题:Printing the records between the date range and also the last record if not in date range

I have had asked this question on my previous question post Printing the current value and previous value between the date range But this time I want to be more specific about the date range here.

如您所见,我有以下数据集:

    ID     DATE           TIME     STATUS 
    ---------------------------------------------
    A      01-01-2000     0900     ACTIVE 
    A      05-02-2000     1000     INACTIVE 
    A      01-07-2000     1300     ACTIVE 
    B      01-05-2005     1000     ACTIVE 
    B      01-08-2007     1050     ACTIVE
    C      01-01-2010     0900     ACTIVE
    C      01-05-2010     0800     INACTIVE
    C      01-07-2010     1900     ACTIVE

我想要以下日期范围(2010年4月1日至2010年6月1日)之间的所有ID。输出应为:

ID     DATE           TIME     STATUS 
---------------------------------------------
A      01-07-2000     1300     ACTIVE 
B      01-08-2007     1050     ACTIVE
C      01-01-2010     0900     ACTIVE 
C      01-05-2010     0800     INACTIVE

这个想法是,如果你看到每个ID的最后一条记录,无论它是否属于该日期范围,因为我希望状态显示自该特定日期以来,ID=A状态没有改变。此外,如果您看到ID=C,则这两个日期都属于日期范围,因此应同时打印这两个。

PS:日期采用DATE格式和MS SQL

如果有人能对此发表意见,我将不胜感激。谢谢你的时间。

问题回答

尝试使用SET DATEFORMAT ymd并进行以下查询:

DATEFORMAT ymd

SELECT customerName 
FROM dbo.customer 
WHERE insertedDate BETWEEN  2010-04-01  AND  2010-06-01 

如果我理解正确的话,你想要:

  1. Any ID whose status within the specified range, and
  2. The most recent active status not in

在这里,我调用您的源表STATS

DECLARE @START DATE =  1/4/2010 ;
DECLARE @END DATE =  1/6/2010 ;

; WITH a AS (
    SELECT *,r=ROW_NUMBER()OVER(PARTITION BY [ID],[STATUS] ORDER BY [DATE] DESC, [TIME] DESC)
    FROM [STATS]
)
SELECT [ID], [DATE], [TIME], [STATUS] FROM a
WHERE [DATE] BETWEEN @START AND @END

UNION

SELECT [ID], [DATE], [TIME], [STATUS] FROM a
WHERE [STATUS]= ACTIVE 
AND r=1;

后果

ID   DATE       TIME STATUS
---- ---------- ---- ----------------
A    2000-01-07 1300 ACTIVE
B    2007-01-08 1050 ACTIVE
C    2010-01-05 0800 INACTIVE
C    2010-01-07 1900 ACTIVE




相关问题
Export tables from SQL Server to be imported to Oracle 10g

I m trying to export some tables from SQL Server 2005 and then create those tables and populate them in Oracle. I have about 10 tables, varying from 4 columns up to 25. I m not using any constraints/...

SQL server: Can NT accounts be mapped to SQL server accounts

In our database we have an SQL server account that has the correct roles to access some of the databases. We are now switching to windows authentication and I was wondering if we can create a NT user ...

SQL Server 2000, ADO 2.8, VB6

How to determine if a Transaction is active i.e. before issuing Begin Transaction I want to ensure that no previous transaction are open.. the platform is VB6, MS-SQL Server 2000 and ADO 2.8

热门标签