T-SQL -- 查找具有与另一列的多个值出现相关联的一列值的行
T-SQL -- find rows with one column value that are associated with multiple value occurrences of another column
T-SQL -- 查找具有与另一列的多个值出现相关联的一列值的行。
目标是找到 table1.col1 值的出现次数,这些值对 table1.col2 有多个值。 (注意:table 中的值不是固定的,例如,我们不是在搜索 "ABC" 等模式,而是必须是特定值。)
(Group by
会找到 对 个相同的 (col1,col2) 元组。)
实际上我有一些我认为理论上正确但在我的系统上运行非常非常慢的代码:
-- find examples where the 1st-column value exists on more than one second-column value to test this.
Select TOP 10 [Col_1], count(1) as countRows_outer from
(
SELECT [Col_2]
,[Col_1]
,count(1) as countRowsInner
FROM [OurDatabase].[dbo].[OurTable]
WHERE
(
(Col_1 is not null)
and
(len (Col_1) > 0)
)
group by [Col_2] ,[Col_1] -- after studying: Inner group by *NOT* needed
having (count(1) >= 2) -- not really needed, but limits search set, faster query results
--order by [Col_1], [Col_2] -- , countRows desc
)c1
group by Col_1
having(count(1) >= 2) -- > 1 (per answer below, may be more efficient here)
order by countRows_outer desc
在上面的代码中,内部 'having' 子句并不是真正需要的,"top" 关键字也不是真正需要的,但它们可以加快速度。
有没有人有更好的方法,或者加快速度的方法。
对于此示例,所有列都是 nvarchar(255)。
我将 SSMS 14.017 与 select 的基础 SQL 数据库一起使用 @@version = Microsoft SQL Server 2014 (SP3)
你不能用一个简单的 GROUP BY 来做到这一点吗
SELECT col1
FROM
table
GROUP BY col1
HAVING COUNT(DISTINCT col2)> 1
这应该让您出现 table1.col1 值,这些值具有 table1.col2 的多个值
T-SQL -- 查找具有与另一列的多个值出现相关联的一列值的行。
目标是找到 table1.col1 值的出现次数,这些值对 table1.col2 有多个值。 (注意:table 中的值不是固定的,例如,我们不是在搜索 "ABC" 等模式,而是必须是特定值。)
(Group by
会找到 对 个相同的 (col1,col2) 元组。)
实际上我有一些我认为理论上正确但在我的系统上运行非常非常慢的代码:
-- find examples where the 1st-column value exists on more than one second-column value to test this.
Select TOP 10 [Col_1], count(1) as countRows_outer from
(
SELECT [Col_2]
,[Col_1]
,count(1) as countRowsInner
FROM [OurDatabase].[dbo].[OurTable]
WHERE
(
(Col_1 is not null)
and
(len (Col_1) > 0)
)
group by [Col_2] ,[Col_1] -- after studying: Inner group by *NOT* needed
having (count(1) >= 2) -- not really needed, but limits search set, faster query results
--order by [Col_1], [Col_2] -- , countRows desc
)c1
group by Col_1
having(count(1) >= 2) -- > 1 (per answer below, may be more efficient here)
order by countRows_outer desc
在上面的代码中,内部 'having' 子句并不是真正需要的,"top" 关键字也不是真正需要的,但它们可以加快速度。
有没有人有更好的方法,或者加快速度的方法。
对于此示例,所有列都是 nvarchar(255)。
我将 SSMS 14.017 与 select 的基础 SQL 数据库一起使用 @@version = Microsoft SQL Server 2014 (SP3)
你不能用一个简单的 GROUP BY 来做到这一点吗
SELECT col1
FROM
table
GROUP BY col1
HAVING COUNT(DISTINCT col2)> 1
这应该让您出现 table1.col1 值,这些值具有 table1.col2 的多个值