【发布时间】:2019-04-12 19:11:42
【问题描述】:
T-SQL -- 查找具有一个列值且与另一列的多个值相关联的行。
目标是查找 table1.col1 值的出现,其中 table1.col2 具有多个值。 (注意:任一表中的值都不是固定的,例如我们不是在搜索“ABC”等模式,但必须是特定值。)
(Group by 会找到 pairs 个相同的 (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
在上面的代码中,内部的“have”子句并不是真正需要的,“top”关键字也不是真正需要的,但它们加快了速度。
有没有人有更好的方法,或者可以加快速度。
对于本例,所有列都是 nvarchar(255)。
我将 SSMS 14.017 与 select @@version = Microsoft SQL Server 2014 (SP3) 的底层 SQL 数据库一起使用
【问题讨论】:
-
不知道为什么这里会有反对票?
标签: tsql search group-by query-optimization sql-server-2014