假设我有下表:
CREATE TABLE person
(
key integer NOT NULL AI ,
name varchar NOT NULL DEFAULT 0,
column1 integer NOT NULL DEFAULT 0,
column2 integer NOT NULL DEFAULT 0,
column3 integer NOT NULL DEFAULT 0,
column4 integer NOT NULL DEFAULT 0,
column5 integer NOT NULL DEFAULT 0,
column6 integer NOT NULL DEFAULT 0,
CONSTRAINT pk PRIMARY KEY (key)
)
现在我想要一个sql,它为我提供了列列为column1到column6的至少两列非零值的行。
e.g。如果我们有行
1 TEST 0 0 6 1 0 5
2 ABCD 0 0 0 0 0 5
3 DEFG 0 0 4 1 0 5
4 HIJK 0 0 0 1 0 0
所以我的查询应返回ID 1和3,因为它们至少有2个非零列。
答案 0 :(得分:3)
试试这个:
SELECT *
FROM person
WHERE (column1 <> 0 + column2 <> 0 + column3 <> 0 +
column4 <> 0 + column5 <> 0 + column6 <> 0
) > 1;
或强>
SELECT p.*
FROM person p
INNER JOIN (SELECT A.key
FROM (SELECT p.key, p.column1 AS columnData FROM person p WHEN p.column1 <> 0
UNION ALL
SELECT p.key, p.column2 AS columnData FROM person p WHEN p.column2 <> 0
UNION ALL
SELECT p.key, p.column3 AS columnData FROM person p WHEN p.column3 <> 0
UNION ALL
SELECT p.key, p.column4 AS columnData FROM person p WHEN p.column4 <> 0
UNION ALL
SELECT p.key, p.column5 AS columnData FROM person p WHEN p.column5 <> 0
UNION ALL
SELECT p.key, p.column6 AS columnData FROM person p WHEN p.column6 <> 0
) AS A
GROUP BY A.key
HAVING COUNT(*) > 1
) AS A ON p.key = A.key;
答案 1 :(得分:0)
计算0列的数量:
where case when c1 = 0 then 1 else 0 end + case when c2 = 0 then 1 else 0 end ... >= 2