我正在研究SQL Server的查询,我想知道是否有人可以给我一些关于选择构成组的单个行的提示(其中组基于聚合函数,在这种情况下为COUNT)< / p>
所以,作为一个简单的例子,如果我有一个账单表,如下所示,我想为每个客户选择在特定日期之后有2个或更多账单的所有账单。
ClaimID ClaimDate ClientName
101 May 5, 2010 Jim
102 June 19, 2010 Jim
103 August 5, 2008 Jim
104 January 1, 2011 Mary
105 May 8, 2009 Mary
106 November 4, 2010 Mary
107 October 6, 2010 Mary
108 April 4, 2010 Bob
109 April 29, 2009 Bob
110 July 7, 2006 Joe
所以如果我执行
SELECT ClientName, COUNT(ClaimID) FROM Billings
WHERE ClaimDate > '2010'
Group By ClientName
Having COUNT(ClaimID) > 1
我会得到:
Jim 2
Mary 3
哪个好,它找到所有在时间范围内有2个或更多账单的客户,但我想列出那些账单是什么。 所以我想要这个:
ClaimID ClientName Count
101 Jim 2
102 Jim 2
104 Mary 3
106 Mary 3
107 Mary 3
您认为实现这一目标的最佳方法是什么?
感谢。
答案 0 :(得分:10)
您将其加入主表。
SELECT B.ClaimID, B.ClaimDate, B.ClientName, G.ClaimCount
FROM
(
SELECT ClientName, COUNT(ClaimID) ClaimCount
FROM Billings
WHERE ClaimDate > '2010'
Group By ClientName
Having COUNT(ClaimID) > 1
) G
INNER JOIN Billings B on B.ClientName = G.ClientName
WHERE B.ClaimDate > '2010'
答案 1 :(得分:4)
假设SQL Server 2005或更高版本,您可以使用公用表表达式
With MultipleBillings As
(
Select ClaimId, ClaimDate, ClientName
, Count(ClaimId) Over ( Partition By ClientName ) As BillingCount
From Billings
Where ClaimDate > '2010'
)
Select ClaimId, ClaimDate, ClientName
From MultipleBillings
Where BillingCount > 1
答案 2 :(得分:1)
Select ClaimID, ClientName, Count From Billings
Where ClientName In (SELECT ClientName FROM Billings
WHERE ClaimDate > '2010'
Group By ClientName
Having COUNT(ClaimID) > 1) And ClaimDate > '2010'
这将生成一个客户名称列表,然后选择具有这些名称的客户端的所有声明。