[英]SQL: Select all rows that meet a condition if that condition is met, but only a certain nuber rows if it isn't
我對我需要編寫的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
有人有想法么? 謝謝
按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
您可以使用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)
這樣的事情應該可以解決您的問題? 您甚至可以將其作為子選擇
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.