如何计算sql中的重复列值

时间:2016-01-15 12:20:17

标签: sql count sum distinct

我有表格&test; testql1'如下:

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

我必须按如下方式选择数据

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

基本上我只想要'评论'数据和计算出的col3,它应该告诉重复的数据' myid'为所有'评论'作为col1。 col2的条件是它是二进制的,当col1是'回顾'

时,它总是包含值1

我试过以下

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

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

4 个答案:

答案 0 :(得分:0)

您可以使用:

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

LiveDemo

输出:

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

答案 1 :(得分:0)

试试这个

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

答案 2 :(得分:0)

试试这个

选择col1,count(myid)为col3 来自testsql1 其中col1 ='评论' 按col1分组;

答案 3 :(得分:-1)

你可以这样使用......

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