2013-04-08 148 views
-1

的輸出我有2個表:合併兩個查詢

SalesOrder - 有2條

OrderID Order Desc 
101  My Order1 
102  My Order2 

SalesOrderLine - 具有以下記錄:

OrderID Order_Line 
101  10 
101  20 
102  10 
102  20 
102  30 

我預期的結果是,當我執行查詢,它應該給我:

  • TotalSalesordercount爲2;和
  • LineCount2 for Order 1013 for Order 102

回答

0
select 
    t1.orderid, 
    count(distinct t1.orderid) as 'TotalSalesordercount', 
    count(*) as 'LineCount' 
from 
    SalesOrder T1, 
    SalesOrderLine T2 
where 
    t1.orderid = t2.orderid 
group by 
    t1.orderid 
0

您將要JOIN兩個表上OrderId,然後使用聚合函數:

select so.orderid, 
    so.order_desc, 
    count(ol.orderid) LineCount, 
    (select count(*) from salesorder) TotalOrders 
from salesorder so 
inner join orderline ol 
    on so.orderid = ol.orderid 
group by so.orderid, so.order_desc; 

SQL Fiddle with Demo

0

東西像這樣可以用於你的數據:

select so.OrderId 
    , TotalSalesordercount = (select count(distinct OrderId) from SalesOrderLine) 
    , LineCount = count(1) 
from SalesOrder so 
    inner join SalesOrderLine sol on so.OrderId = sol.OrderId 
group by so.OrderId 

SQL Fiddle with demo