复杂的SQL查询

时间:2011-08-14 11:16:25

标签: sql sql-server-2008

我的数据库如下所示:

  • Customer (c_id, c_name)
  • Products (p_id, p_name, p_cost)
  • Buys (p_id references Products, c_id references Customer)

我想查询数据库以获取以下信息:

  • 拥有最多产品数量的客户:如果有2个或更多客户拥有相同数量的产品,则认为所有产品的总价格

我试了一下,但它显示错误说:“语法不正确”“。

我试图调试它以获得无益。

任何人都可以调试此查询,甚至建议更优化的查询吗?

select a1.c_id, a1.c_name 
from
    (select c.c_id, c.c_name
     from Customer c
     where c.c_id in
         (select b.c_id
          from Buys b
          group by b.c_id
          having COUNT(b.p_id) >= all
          (
              select COUNT(b.p_id)
              from Buys b
              group by b.c_id
          )
    )
) 
as a1 
join 
   (select b.c_id, SUM(p.p_cost) as 'SumCost'
    from Buys b 
    join Products p on b.p_id = p.p_id
    group by b.c_id
   ) as a2 on a1.c_id = a2.c_id
where 
    a2.SumCost = (select MAX(SumCost)
                  from 
                      (select b.c_id, SUM(p.p_cost) as 'SumCost' 
                       from Buys b 
                       join Products p on b.p_id = p.p_id
                       group by b.c_id
                      )
                 )

更新:

上面的查询由mohdowais成功调试。 我现在认为这个查询效率不高。你们都可以建议一个更高效的吗? 我没有使用任何索引。

1 个答案:

答案 0 :(得分:2)

您需要为最后一个选择添加派生表说明符:

select a1.c_id,a1.c_name 
    from
    (
    select c.c_id,c.c_name
    from Customer c
    where c.c_id in
    (
        select b.c_id
        from Buys b
        group by b.c_id
        having COUNT(b.p_id)>=all
        (
            select COUNT(b.p_id)
            from Buys b
            group by b.c_id
        )
    )
) 
as a1 join   (
                    select b.c_id,SUM(p.p_cost) as 'SumCost'
                    from Buys b join Products p on (b.p_id=p.p_id)
                    group by b.c_id
                 )  
                 as a2  on (a1.c_id=a2.c_id) 

                 where a2.SumCost=
                 (
                    select MAX(SumCost)
                    from 
                    (
                        select b.c_id,SUM(p.p_cost) as 'SumCost' 
                        from Buys b join Products p on (b.p_id=p.p_id)
                        group by b.c_id
                    ) maxTmp    -- <-----------------
                 )

[我不能评论您的查询的正确性或效率,但没有表格架构,索引和示例数据]