0

我有下表,
我想找到最大值(account_opened_date),如果存在空日期,我必须显示空值。

场景1

表格1

CLIENTID            ACCOUNTID           ACCOUNT_OPENED_DATE
11562               3880                07/05/2012
11562               3884                08/05/2012
11562               3885                09/06/2012
11562               3886                10/06/2012
11562               3881                NULL
11562               3882                NULL  

结果如下。

CLIENTID            ACCOUNTID           ACCOUNT_OPENED_DATE  
11562               3882                NULL  

在上述情况下,我必须取空值,因为开户日期中存在空值

情景2

表格1

CLIENTID            ACCOUNTID           ACCOUNT_OPENED_DATE  
11563               3880                07/05/2012
11563               3884                08/05/2012
11563               3885                09/06/2012
11563               3886                10/06/2012
11563               3881                11/10/2011
11563               3882                10/22/2012  

结果如下。

CLIENTID            ACCOUNTID           ACCOUNT_OPENED_DATE
11563               3882                10/22/2012  

在上述情况下,我必须选择 2012 年 10 月 22 日,因为在开户日期中不存在空值,
请帮助!

4

2 回答 2

2

您可以选择TOP 1获取一条记录并ORDER BY CASE满足您的“null-first”要求:

SELECT TOP 1 CLIENTID, ACCOUNTID, ACCOUNT_OPENED_DATE
FROM dbo.Table
ORDER BY CASE WHEN ACCOUNT_OPENED_DATE IS NULL THEN 0 ELSE 1 END ASC
  , ACCOUNT_OPENED_DATE DESC
  , ACCOUNTID DESC        
于 2012-10-22T20:19:32.180 回答
1

试试这个

SELECT * FROM (
SELECT CLIENTID, ACCOUNTID, ACCOUNT_OPENED_DATE, 
ROW_NUMBER() OVER (partition by clientid 
             ORDER BY CASE WHEN ACCOUNT_OPENED_DATE IS NULL THEN '12/31/9999' 
                      ELSE ACCOUNT_OPENED_DATE END DESC) opened_date_rank
FROM dbo.Table1
) v WHERE opened_date_rank = 1 

例子:

declare @table table (clientid int, accountid int, opened_date date)
insert into @table 
select 11562, 3880, '07/05/2012' UNION ALL
select 11562,3884, '08/05/2012' UNION ALL
select 11562,3882, null UNION ALL
select 11563,3880, '07/05/2012' UNION ALL
select 11563,3884, '08/05/2012' UNION ALL
select 11563,3882,'10/22/2012'



SELECT * FROM (
SELECT clientid, accountid, opened_date, 
row_number() over (partition by clientid 
             ORDER BY CASE WHEN opened_date IS NULL THEN '12/31/9999' 
                      ELSE opened_date END DESC) opened_date_rank
FROM @table
) v where opened_date_rank = 1 
于 2012-10-22T20:28:20.647 回答