组中的SQL过滤器

时间:2018-04-19 12:01:28

标签: sql group-by

我有一个包含一个表的数据库:

+-------+------+--+
| Col1  | Col2 |  |
+-------+------+--+
| Auto  | alt  |  |
| Auto  | alt  |  |
| Auto  | neu  |  |
| Haus  | alt  |  |
| Haus  | alt  |  |
| Stuhl | neu  |  |
+-------+------+--+

现在我想让Col1中的所有组都有多个像Auto和Haus这样的重复。我这样做了:

SELECT talbe1.Col1, talbe1.Col2
FROM table1
WHERE talbe1.Col1 In (SELECT Col1 FROM talbe1.Col1 As Tmp GROUP BY Col1 HAVING Count(Col1)>1)
ORDER BY talbe1.Col1;

此外,我现在只想在Col2中的值与Auto中的值不同时才想要这些组。结果如下:

+------+------+--+
| Col1 | Col2 |  |
+------+------+--+
| Auto | alt  |  |
| Auto | alt  |  |
| Auto | neu  |  |
+------+------+--+

有人可以帮我在SQL中如何做到这一点吗?

3 个答案:

答案 0 :(得分:1)

您可以使用exists

select * from table t
where exists (select 1 from table 
              where Col1 = t.Col1 
              group by Col1 
              having count(distinct Col2) > 1);

答案 1 :(得分:0)

SELECT t3.Col1,t3.Col2
FROM table1 t3
INNER JOIN
(
SELECT t1.Col1
FROM (SELECT Col1,Col2,COUNT(*) AS cn FROM table1 GROUP BY Col1,Col2) t1
INNER JOIN
(
SELECT Col1,COUNT(*) AS cn
FROM table1
GROUP BY Col1
HAVING COUNT(*) > 1
) t2
ON t1.Col1=t2.Col1 AND t1.cn != t2.cn
GROUP BY t1.Col1
) t4
ON t3.col1=t4.col1

<强>输出

Col1    Col2
Auto    alt
Auto    alt
Auto    neu

<强>演示

  

http://sqlfiddle.com/#!9/24b3ec/33

答案 2 :(得分:0)

您可以使用子查询在列中查找满足条件的值,然后获取其余必要信息:

DECLARE @Table TABLE (col1 VARCHAR(max), col2 VARCHAR(max)) 

INSERT INTO @Table (col1, col2)
values
('Auto', 'alt'),
('Auto', 'alt'),
('Auto', 'neu'),
('Haus', 'alt'),
('Haus', 'alt'),
('Stuhl', 'neu')

SELECT *
FROM @Table
WHERE col1 IN (
    SELECT col1
    FROM @Table
    GROUP BY col1
    HAVING COUNT(*) > 1 
    AND COUNT(DISTINCT col2) > 1 
)

条件在哪里:

HAVING COUNT(*) > 1 

在列col1

中查找所有重复值

这个条件:

AND COUNT(DISTINCT col2) > 1 

查找列col2具有非唯一值

的记录