我有一个表,我想检查一列的所有值是否相同。
以下是我表格中的条目。
两栏
rid,value
(1,1)
(1,1)
(2,1)
(2,0)
(2,0)
(3,0)
(3,0)
(3,0)
我想查询哪个让我摆脱1,因为它的所有值都是1.所有记录对于rid 1都有值1而rid 2和3没有将所有值都作为1所以它们不应该被选中。
答案 0 :(得分:2)
使用group by和having可以得到你想要的东西:
SELECT rid, value
FROM my_table
GROUP BY rid
HAVING COUNT( distinct value) = 1
<强>更新强>
根据评论,过滤该值将得到结果:
SELECT *
FROM
(
SELECT rid, value
FROM my_table
GROUP BY rid
HAVING COUNT( distinct value) = 1
) AS T1
WHERE value = 1
如果值只有1或0,那么你可以做到这一点:
SELECT rid, value
FROM my_table
GROUP BY rid
HAVING COUNT( * ) = SUM(value)
答案 1 :(得分:0)
你可以这样做:
CREATE TABLE my_table (
id varchar(255),
col_value varchar(255)
);
INSERT INTO my_table
VALUES
('1','1'),
('1','1'),
('2','1'),
('2','1'),
('2','1'),
('2','4'),
('3','1'),
('3','1');
查询选择:
SELECT src.* FROM
(
SELECT DISTINCT t1.* FROM my_table AS t1
) AS src
WHERE src.id NOT IN(
SELECT test.id
FROM
(
SELECT DISTINCT t1.* FROM my_table AS t1
) AS test
GROUP BY test.id
HAVING COUNT(*) > 1
)
fiddle此处。