SQL having 语句现在需要完整的行
SQL with having statement now want complete rows
这是一个模拟table
MYTABLE ROWS
PKEY 1,2,3,4,5,6
COL1 a,b,b,c,d,d
COL2 55,44,33,88,22,33
我想知道哪些行具有重复的 COL1 值:
select col1, count(*)
from MYTABLE
group by col1
having count(*) > 1
这个returns:
b,2
d,2
我现在想要包含 b 和 d 的所有行。通常,我会使用 where in stmt,但是对于计数列,不确定我应该使用哪种类型的语句?
也许你需要
select * from MYTABLE
where col1 in
(
select col1
from MYTABLE
group by col1
having count(*) > 1
)
使用 CTE 和窗口聚合:
WITH CTE AS(
SELECT Pkey,
Col1,
Col2,
COUNT(1) OVER (PARTITION BY Col1) AS C
FROM dbo.YourTable)
SELECT PKey,
Col1,
Col2
FROM CTE
WHERE C > 1;
有很多方法可以解决这个问题
select * from MYTABLE
join
(
select col1 ,count(*)
from MYTABLE
group by col1
having count(*) > 1
) s on s.col1 = mytable.col1;
这是一个模拟table
MYTABLE ROWS
PKEY 1,2,3,4,5,6
COL1 a,b,b,c,d,d
COL2 55,44,33,88,22,33
我想知道哪些行具有重复的 COL1 值:
select col1, count(*)
from MYTABLE
group by col1
having count(*) > 1
这个returns:
b,2
d,2
我现在想要包含 b 和 d 的所有行。通常,我会使用 where in stmt,但是对于计数列,不确定我应该使用哪种类型的语句?
也许你需要
select * from MYTABLE
where col1 in
(
select col1
from MYTABLE
group by col1
having count(*) > 1
)
使用 CTE 和窗口聚合:
WITH CTE AS(
SELECT Pkey,
Col1,
Col2,
COUNT(1) OVER (PARTITION BY Col1) AS C
FROM dbo.YourTable)
SELECT PKey,
Col1,
Col2
FROM CTE
WHERE C > 1;
有很多方法可以解决这个问题
select * from MYTABLE
join
(
select col1 ,count(*)
from MYTABLE
group by col1
having count(*) > 1
) s on s.col1 = mytable.col1;