SQL组没有获得最高记录

时间:2013-01-22 09:42:33

标签: sql sql-server

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

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

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中使用最长的日期。
  4. 因此,对于上述记录样本,我需要输出为

    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
    

2 个答案:

答案 0 :(得分:0)

我认为你的代码过于复杂和冗余。 您应该创建一个SQL函数来获取enddate。 调用此函数getEndDate(String date)(我想你可以自己创建它)

你的查询可能是:

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

然后你走第一排。

答案 1 :(得分: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上的演示