DB2-如何查找计数多次出现的列值

时间:2019-01-11 19:10:50

标签: sql db2

我是DB2的新手,并根据一些类似的文章进行了尝试,我有一个表格,我需要根据status = P和  (primary = 1)的计数超过一次。 所以我的结果应该是2-(9876,3456) 尝试过:

SELECT id, COUNT(isprimary) Counts
  FROM table 
 GROUP BY id
HAVING COUNT(isprimary)=1;

enter image description here

2 个答案:

答案 0 :(得分:2)

您很亲密,我想您需要做的就是添加一个where子句,如:

SELECT id, COUNT(*) as Counted
FROM table 
WHERE PrimaryFlag = 1 
  AND[status] = 'P'
GROUP BY id

编辑:如果只需要计算不同的ID,请尝试:

SELECT COUNT(t.ID) FROM
(
    SELECT id, COUNT(*) as Counted
    FROM table 
    WHERE PrimaryFlag = 1 
      AND[status] = 'P'
    GROUP BY id
) as t

答案 1 :(得分:0)

请尝试以下查询:

select ID as IDs,Count(isPrimary) as isPrimary
From Table
where Status = 'p' 
Group by ID
Having Count(isPrimary) >1