分组来自两个表

时间:2013-10-21 09:38:49

标签: sql sql-server database sql-server-2008

我要求从两个不同的表格中显示以下格式的报告,如下所示,下面的报告应按分支计算订单编号。

===================================================================
Branch     OrdersCountInTable1           OrdersCountInTable2
===================================================================
    100            5                           2
    200            10                          10
    300            12                          11

如何使用sqlquery实现此目的?

以下是表格中的列:

Table1:
________
 - Branch
 - OrderNo

Table2
__________
 - Branch  
 - OrderNo

表1数据:

===============================
Branch             OrderNo      
===============================
    100            1000                 
    100            1001              
    200            2001
    100            1003

表2数据:

===============================
Branch             OrderNo      
===============================
    100            1000                                    
    200            2001
    100            1003

我们只想调和两张桌子的订单!! 感谢您提供任何有价值的反馈。

3 个答案:

答案 0 :(得分:0)

一种或多或少的通用方式

SELECT COALESCE(t1.branch, t2.branch) branch, 
       COALESCE(t1.ordercount, 0) OrdersCountInTable1, 
       COALESCE(t2.ordercount, 0) OrdersCountInTable2
  FROM
(
  SELECT branch, COUNT(orderno) ordercount
    FROM Table1
   GROUP BY branch
) t1 FULL JOIN
(
  SELECT branch, COUNT(orderno) ordercount
    FROM Table2
   GROUP BY branch
) t2
 ON t1.branch = t2.branch

假设表格可能没有所有分支的条目。这就是使用FULL JOIN的原因。

答案 1 :(得分:0)

使用SUM聚合函数和UNION ALL运算符

这样做
SELECT Branch,
       SUM( CASE tag WHEN 'table1' THEN 1 ELSE 0 END) as OrdersCountInTable1,
       SUM( CASE tag WHEN 'table2' THEN 1 ELSE 0 END) as OrdersCountInTable2
FROM
(

SELECT Branch,'table1' as tag
FROM Table1

UNION ALL

SELECT Branch,'table2' as tag
FROM Table2

) z

GROUP BY Branch
ORDER BY Branch

答案 2 :(得分:0)

使用union嵌套查询尝试:

select 
  Branch, count(Orders1) OrdersCountInTable1, count(Orders2) OrdersCountInTable2
from (
  select Branch,OrderNo Orders1,NULL Orders2 from Table1
  union
  select Branch,NULL Orders1,OrderNo Orders2 from Table2
  ) t
group by Branch