如何在连接表中进行汇总?

时间:2015-12-15 20:41:50

标签: sql sql-server

我有三张桌子:

  • " Item_Table"
  • " Order_Table"
  • " Order_Scores"

" Item_Table"使用" code1"可以连接"代码"到" Order_Scores"

" Order_Table"用"数字"可以连接"数字"到" Order_Scores"

我需要总结一下" count"列" Order_Scores"按"代码"分组的人clolumn和" type"列是" req"。

我写了这个查询:

select Item_Table.*,
(select SUM(cast (Order_Scores.count AS INT)) from Order_Table left outer join Order_Scores on Order_Table.number=Order_Scores.number where Order_Table.type='req' group by Order_Scores.code ) AS ReqOrderTotall
from Item_Table left outer join Order_Scores on Item_Table.code1= Order_Scores.code 

...但我收到了一个错误:

  

Msg 512,Level 16,State 1,Line 1      子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

2 个答案:

答案 0 :(得分:0)

这是您的查询:

select Item_Table.*,
       (select SUM(cast (Order_Scores.count AS INT))
        from Order_Table left outer join
             Order_Scores
             on Order_Table.number=Order_Scores.number
             where Order_Table.type = 'req'
        group by Order_Scores.code
       ) AS ReqOrderTotall
from Item_Table left outer join
     Order_Scores
     on Item_Table.code1 = Order_Scores.code ;

此查询存在多个问题,但您的问题是由子查询中的group by引起的。正如错误消息所示,这将返回多行。此外,您不需要外部查询中的Order_Scores表。结果是这样的,虽然我不确定相关性是否正确:

select it.*,
       (select SUM(cast(Order_Scores.count AS INT))
        from Order_Table ot join
             Order_Scores os
             on ot.number = os.number
        where ot.type = 'req' and ot.item_id = it.item_id
----------------------------------^
       ) AS ReqOrderTotall
from Item_Table it;

答案 1 :(得分:0)

绝不使用相关子查询。他们是性能杀手。改为使用派生表。

select Item_Table.*,Totals.ReqOrderTotal
 from Item_Table 
left outer join  Order_Scores
     on Item_Table.code1 = Order_Scores.code 
left outer join
 (select  Order_Scores.code, SUM(cast (Order_Scores.count AS INT))as ReqOrderTotal
        from Order_Table left outer join
             Order_Scores
             on Order_Table.number=Order_Scores.number
             where Order_Table.type = 'req'
        group by Order_Scores.code
       ) Totals
      on Totals.code= Order_Scores.code 

当然,使用select *是一个SQL反模式,所以请用你需要的实际字段名替换它。