代码之家  ›  专栏  ›  技术社区  ›  NimChimpsky

使用两个全表扫描CTE优化SQL、现有查询

  •  1
  • NimChimpsky  · 技术社区  · 15 年前

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

    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 
    
    2 回复  |  直到 15 年前
        1
  •  3
  •   Joe Stefanelli    15 年前
    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
    
        2
  •  0
  •   user359040 user359040    15 年前

    最简单的答案是:

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

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