如何计算 sql 中的重复列值

How to count the duplicate column values in sql

我有 table 'testsql1' 的值如下:

(myid (int), col1 (nvarchar), col2 (binary)) 
VALUES (10, 'Prod', 0), (10, 'Test', 0), (10, 'Review', 1),
       (11,'Prod', 0), (11, Review, 1)

我要select数据如下

(myid, col1, col3) 
VALUES (10, Review, 3), (11, Review, 2)

基本上我只需要 'Review' 数据和一个计算的 col3,它应该告诉所有 'Review' 的重复 'myid' 的计数作为 col1。 col2 的条件是它是二进制的,并且当 col1 为 'Review'

时始终包含值 1

我试过以下方法

select myid, col1, count(myid) as col3
from testsql1
where col1 = 'Review'
group by myid, col1;

但它只是给我两个 myid(10 和 11)的 col3 值为 1

您可以使用:

select myid, 'Review' AS col1, count(myid) as col3
from testsql1
group by myid;

LiveDemo

输出:

╔══════╦════════╦══════╗
║ myid ║  col1  ║ col3 ║
╠══════╬════════╬══════╣
║   10 ║ Review ║    3 ║
║   11 ║ Review ║    2 ║
╚══════╩════════╩══════╝

你可以这样使用...

select myid, 'Review' as col1, count(myid) as col3
from testsql1
group by myid;

试试这个

select distinct a.myid,'Review' as col1,a.col3
From (select myid, count(myid) as col3
from testsql1
group by myid) a,testsql1 b
where col1 = 'Review' and a.myid = b.myid

试试这个

select col1, count(myid) 作为 col3 来自 testsql1 其中 col1='Review' 按 col1 分组;