【问题标题】:Optimizing sql, existing query using two full table scans CTE's使用两个全表扫描优化 sql,现有查询 CTE
【发布时间】:2010-11-04 22:42:46
【问题描述】:

我正在寻找对以下查询的改进,感谢任何输入

with cteA as (
        select name, count(1) as "A" 
        from mytable 
        where y="A"
        group by name
    ),
    cteB as (
            select name, count(1) as "B" 
            from mytable 
            where y="B"
            group by name

    )
    SELECT  cteA.name as 'name',
        cteA.A as 'count x when A',
        isnull(cteB.B as 'count x when B',0)
    FROM
    cteOne 
    LEFT OUTER JOIN 
    cteTwo
    on cteA.Name = cteB.Name
    order by 1 

【问题讨论】:

    标签: sql tsql optimization


    【解决方案1】:
    select name, 
           sum(case when y='A' then 1 else 0 end) as [count x when A],
           sum(case when y='B' then 1 else 0 end) as [count x when B]
        from mytable
        where y in ('A','B')
        group by name
        order by name
    

    【讨论】:

    • 当然,如果字段 Y 和名称被索引也会很有帮助。
    【解决方案2】:

    最简单的答案是:

    select name, y, count(*)
    from mytable
    where y in ('A','B')
    group by name, y
    

    您可以使用 PIVOT 将 Y 行值移动到列中,如果您需要它们在列中。

    【讨论】:

      猜你喜欢
      • 2011-05-19
      • 1970-01-01
      • 1970-01-01
      • 2014-08-21
      • 1970-01-01
      • 2021-12-08
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多