1

下面是我表中的示例记录。

字段为 varchar,ToDate 包含两条空记录。(不是数据库 NULL)

CustomerID  FromDate    ToDate
1           20120810    20120920
2           20120901    20120915
3           20120112    
4           20120815    
5           20120817    20120920
6           20120817    20120920

必须遵守以下规则:

  1. 以 ToDate 列中最远的日期排序。
  2. 当记录为空时,取当前日期+30 而不是空,
  3. 当 ToDate 中的两个日期相同时,取 FromDate 中最远的日期。

所以对于上述记录样本,我需要输出为

CustomerID   FromDate   ToDate
3            20120112   20130221

因为客户 id 4 和 5 ToDate 是空的,所以我们考虑应该从 getdate() 函数中添加 30 天。所以 Todate 是相等的,所以我现在想按 FromDate 排序。

日期的输入是 20120810

select   top 1 customer_id, 
max(convert(datetime,Fromdate,101)) as Fromdate,
convert(datetime,(CASE WHEN Todate = '' THEN getdate() + 30 WHEN Todate != '' THEN Todate END),101) as Todate,
customer_id
FROM  dbo.sample_tbl (nolock)
 WHERE  customer_id = '1' 
 AND    Fromdate <= '20120810'
 AND    (CASE WHEN ToDate = '' THEN getdate() + 30 WHEN ToDate != '' THEN ToDate END) >= '20120810'
group by convert(datetime,(CASE WHEN ToDate = '' THEN getdate() + 30 WHEN ToDate != '' THEN ToDate END),101),customer_id
order by convert(datetime,(CASE WHEN ToDate = '' THEN getdate() + 30 WHEN ToDate != '' THEN ToDate END),101) desc

电流输出为

CustomerID   FromDate  ToDate
3            20120112  20130221

预期是

CustomerID   FromDate   ToDate
3            20120815   20130221
4

2 回答 2

0

我认为你的代码太复杂和多余。您应该创建一个 SQL 函数来获取 enddate。调用这个函数getEndDate(String date)(我觉得你可以自己创建)

您的查询可能是:

select  CustomerID  ,FromDate  , getEndDate (ToDate) 
from sample_tbl
order by getEndDate (ToDate) desc, FromDate  desc  ;

然后你占据第一排。

于 2013-01-22T10:59:32.760 回答
0

在 SQLServer 2005+ 中

 ;WITH cte AS
 ( 
  SELECT CustomerID,         
         MAX(CAST(FromDate AS date)) OVER (PARTITION BY
         (CASE WHEN ToDate = '' THEN CAST(GETDATE() + 30 AS date) ELSE CAST(ToDate AS date) END
         )) AS FromDate,         
         CASE WHEN ToDate = '' THEN CAST(GETDATE() + 30 AS date) ELSE CAST(ToDate AS date) END AS ToDate
  FROM dbo.sample_tbl
  )
  SELECT TOP 1 CustomerID, MAX(FromDate) AS FromDate, ToDate
  FROM cte
  GROUP BY ToDate, CustomerID
  ORDER BY ToDate DESC

SQLFiddle上的演示

于 2013-01-22T11:58:02.773 回答