我有如下表,
我想找到max(account_opened_date),如果存在null 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
在上面的场景中,我必须取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
在上面的场景中,我必须采取10/22/2012因为,帐户开立日期中不存在空值
请帮助!
答案 0 :(得分:2)
您可以选择TOP 1
获取一条记录,并选择ORDER BY CASE
作为“空优先”要求:
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
答案 1 :(得分: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