我需要编写一个SQL Server 2005查询,并且它让我知道如何完成它。 我将简化它,但实质是,如果客户没有比某个日期更近的账单,我需要选择最多3个客户的最近账单。但如果他们在截止日期之后有账单,只需显示任何这些账单。
所以,如果我的截止日期是2010年1月1日,我的数据如下:
ClaimID ClientID BillingDate
1 1 March 12, 2010
2 1 June 3, 2010
3 1 January 5, 2008
4 1 February 9, 2011
5 1 May 19, 2005
6 2 November 20, 2005
7 2 October 5, 2009
8 3 January 4, 1999
9 3 July 8, 1997
10 3 May 7, 2010
11 3 August 6, 1999
12 4 May 25, 2000
13 4 April 1, 2005
14 4 March 9, 2009
15 4 December 5, 2007
16 4 December 19, 1998
17 4 June 3, 2006
然后我想选择:
ClaimID ClientID BillingDate
1 1 March 12, 2010
2 1 June 3, 2010
4 1 February 9, 2011
6 2 November 20, 2005
7 2 October 5, 2009
10 3 May 7, 2010
14 4 March 9, 2009
15 4 December 5, 2007
17 4 June 3, 2006
有人有什么想法吗? 感谢
答案 0 :(得分:4)
通过降序BillingDate
为每个客户排名。
对于每个客户,输出以下日期:
比截止日期更近,或
属于排名最高的3个。
查询:
;WITH ranked AS (
SELECT
*,
rownum = ROW_NUMBER() OVER (PARTITION BY ClientID ORDER BY BillingDate DESC)
FROM Billings
)
SELECT ClaimID, ClientID, BillingDate
FROM ranked
WHERE BillingDate > @CutOffDate OR rownum BETWEEN 1 AND 3
答案 1 :(得分:1)
您可以使用UNION ALL
来合并两个查询的结果:
SELECT *
FROM MyTable
WHERE BillingDate > '1-Jan-2010'
UNION ALL
SELECT *
FROM MyTable T1
WHERE NOT EXISTS (SELECT *
FROM MyTable T2
WHERE T1.ClientID = T2.ClientID AND T2.BillingDate > '1-Jan-2010')
AND ClaimID IN (SELECT TOP 3 T3.ClaimID
FROM MyTable T3
WHERE T1.ClientID = T3.ClientID
ORDER BY T3.BillingDate DESC)
答案 2 :(得分:0)
这样的事情可以解决你的问题吗?如果你想
,你甚至可以将其作为一个子选择select ClaimID, ClientID, BillingDate
from bills
where BillingDate > @cutoffDate
UNION ALL
select ClaimID, ClientID, BillingDate
from bills a
where not exists (select 1 from bills b
where b.ClientId = a.ClientId
and b.BillingDate > @cutoffDate)
and 3 > (select count(1) from bills b
where b.ClientId = a.ClientId
and b.BillingDate>a.BillingDate)