1

我需要查询表中状态列的值为“4”和“7”的行

信息:

select count(def.Defect_id) from defects def where def.State = 4
select count(def.Defect_id) from defects def where def.State = 7

在这里我怎样才能找到有状态“4”和“7”记录的defect_id(非主键)行

(我需要状态 4 的缺陷 ID 计数,它也应该存在于状态 7 中)

4

2 回答 2

2

您可以一次性检索id 的单独计数,如下所示47

SELECT sum(CASE WHEN defect_id = 4 THEN 1 ELSE 0 END) AS cnt4, 
       sum(CASE WHEN defect_id = 7 THEN 1 ELSE 0 END) AS cnt7,
FROM defects

UPDATE1:看起来问题的理解不同。

这应该可行,但前提statedefect_id您的defects表中不超过一个:

SELECT count(d1.*)
FROM defects d1, defects d2
WHERE d1.defect_id = d2.defect_id
  AND d1.state = 4
  AND d2.state = 7

UPDATE2:如果您的表中可以有多个相同的组合(defect_id, state)并且只想为您的 id和计数一次,只需添加如下:47GROUP BY

SELECT count(d1.defect_id)
FROM defects d1, defects d2
WHERE d1.defect_id = d2.defect_id
  AND d1.state = 4
  AND d2.state = 7
GROUP BY
   d1.defect_id,
   d1.state,
   d2.state
于 2013-04-25T07:50:38.523 回答
0

尝试这个:

SELECT count(tbl1.defect_id) 
    FROM defects tbl1 INNER JOIN defects tbl2 on tbl1.defect_id = tbl2.defect_id
    WHERE tbl1.State = 4 AND tbl2.State = 7
于 2013-04-25T07:46:22.327 回答