合并两个查询的输出

时间:2013-04-08 10:36:24

标签: sql tsql

我有两张桌子:

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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