[英]SQL Server query distinct
I'm trying to do a query in SQL Server 2008. This is the structure of my table 我正在尝试在SQL Server 2008中进行查询。这是我的表的结构
Recno ClientNo ServiceNo
---------------------------------
1234 17 27
2345 19 34
3456 20 33
4567 17 34
I'm trying to select RecNo
however, filtering by distinct ClientNo
, so for some clients such as client no 17 - they have more than 1 entry, I'm trying to count that client only once. 但是,我尝试选择
RecNo
, RecNo
不同的ClientNo
过滤,因此对于某些客户端(例如17号客户端)-它们具有1个以上的条目,我尝试仅对该客户端进行一次计数。 So basically, looking at this table, I'm only supposed to see 3 RecNo's, since there are only 3 distinct clients. 所以基本上,看这张表,我只应该看到3个RecNo,因为只有3个不同的客户。 Please help
请帮忙
Select RecNo, Count(ClientNo)
from TblA
where Count(clientNo)<2
Something like this? 像这样吗
EDIT: 编辑:
The value of RecNo
is not relevant, I only need to have an accurate number of records. RecNo
的值RecNo
,我只需要有准确的记录数即可。 In this case, I'd like to have 3 records. 在这种情况下,我想要3条记录。
oaky you are getting some crazy answers probably becuase your desired result is not clear so I suggest if some of these are not what you need that you clarify your desired result. 橡木桶您会得到一些疯狂的答案,可能是因为您所期望的结果不清楚,因此,我建议您澄清其中所期望的结果是否不是您所需要的。
If you want the answer 3, I can only assume you want a count of DISTINCT ClientNo's if so it is simply aggregation. 如果您想要答案3,我只能假设您想要一个DISTINCT ClientNo的计数,如果这样的话,它只是聚合。
SELECT COUNT(DISTINCT ClientNo) as ClientNoDistinctCount
FROM
TblA
GROUP BY
ClientNo
Ok, this will give you the count that you want: 好的,这将为您提供所需的计数:
WITH CTE AS
(
SELECT *,
RN = ROW_NUMBER() OVER(PARTITION BY ClientNo ORDER BY Recno)
FROM TblA
)
SELECT COUNT(DISTINCT Recno) N
FROM CTE
WHERE RN = 1;
Try this.. 尝试这个..
;with cte1
As(SELECT Recno,clientno
,row_number() over(partition by clientno order by Recno )RNO FROM TblA)
Select Recno,clientno
From cre1 where RNO=1
Choose only ClientNo
having the max Recno
(or replace <
with >
to choose the min one). 仅选择具有最大
Recno
ClientNo
(或将<
替换为>
以选择最小的ClientNo
)。
Select *
from TblA t1
where not exists(select 1
from TblA t2
where t1.ClientNo = t2.ClientNo and t1.Recno < t2.Recno )
BTW, the other solution already mentioned, utilizing row_number()
needs no CTE in this case BTW,已经提到的另一个解决方案,在这种情况下,利用
row_number()
不需要CTE
SELECT TOP(1) WITH TIES *
FROM TblA
ORDER BY ROW_NUMBER() OVER(PARTITION BY ClientNo ORDER BY Recno)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.