【问题标题】:T-SQL -- find rows with one column value that are associated with multiple value occurrences of another columnT-SQL——查找具有一个列值且与另一列的多个值相关联的行
【发布时间】: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


【解决方案1】:

你不能用一个简单的 GROUP BY 来做到这一点

SELECT col1
FROM 
    table
GROUP BY col1
HAVING COUNT(DISTINCT col2)> 1

这应该会让您出现 table1.col1 值具有多个 table1.col2 值

【讨论】:

  • 顶部查询中的内部“分组依据”是不需要的,并且只会计算 (col1, col2) 对,因此它会得到不同的结果。我认为答案是更好的查询,并且可以正常工作且速度更快。可能 "> 1" 至少与 ">=2" 一样快,具体取决于底层优化器,甚至编译机器代码,干得好。
  • 我编辑了我的问题以反映上面的 cmets。无论如何,这个答案似乎在各方面都不错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-02
  • 1970-01-01
  • 2016-03-22
  • 1970-01-01
  • 2016-06-04
  • 1970-01-01
相关资源
最近更新 更多