sql查询以查找重复记录并从计数中扣除

k5ifujac  于 2021-08-13  发布在  Java
关注(0)|答案(5)|浏览(270)

我使用下面的sql查询来统计记录。我想在拿到票后把复制的睾丸打折扣。
例子:

select COUNT(*)  from PRODUCT where CLASS_TYPE = 'test'

以上查询给出5条记录

testID
1234-00-01
1234-00-01
1234-00-02
1234-00-02
1111222233

我想得到计数=5-重复2=3
有没有sql查询可以用来找出重复的记录,然后计算最终的计数?

oymdgrw7

oymdgrw71#

请使用下面的查询,

select COUNT(distinct testID)  from PRODUCT where CLASS_TYPE = 'test'
ftf50wuq

ftf50wuq2#

你想要什么 count(distinct) :

select count(distinct testID)
from product p
where p.class_type = 'test'
cwdobuhd

cwdobuhd3#

如果要获取总计数和副本,可以尝试以下sql:

SELECT count(DISTINCT testID) as distinct_elements, count(*) as total_elements, 
      (count(*) - count(DISTINCT testID)) as duplicate_elements 
FROM PRODUCT
WHERE CLASS_TYPE = 'test';
ekqde3dh

ekqde3dh4#

你可以用 distinct :

select count(distinct col) as Unique_CNT, COUNT(*) as all_CNT  
from PRODUCT 
where CLASS_TYPE = 'test';
zynd9foi

zynd9foi5#

CREATE TABLE #Test
( 
testID VARCHAR(100)   
) 

INSERT INTO #Test
(testID)
VALUES
('1234-00-01'),
('1234-00-01'),
('1234-00-02'),
('1234-00-02'),
('1111222233')

select COUNT(distinct testID) from #Test

相关问题