0

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

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

我如何使用 sqlquery 来实现这一点?

以下是表中的列:

Table1:
________
 - Branch
 - OrderNo

Table2
__________
 - Branch  
 - OrderNo

表1数据:

================================
分行订单号      
================================
    100 1000                 
    100 1001              
    200 2001
    100 1003

表2数据:

================================
分行订单号      
================================
    100 1000                                    
    200 2001
    100 1003

我们只想核对两个表的订单!!感谢您提供任何有价值的反馈。

4

3 回答 3

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
于 2013-10-21T10:08:43.973 回答
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使用。

于 2013-10-21T10:05:06.547 回答
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
于 2013-10-21T10:39:30.160 回答