SQL三表连接查询

时间:2014-03-26 07:27:44

标签: sql

我有这个查询

select
  dbo.CLOI_ClientOrderItems.cl_id,
  count(dbo.IN_Invoices.MasterOrderId) as Orders,
  sum(dbo.IN_Invoices.in_total) as Total
from
  IN_Invoices
inner join
  CLOI_ClientOrderItems
on
  IN_Invoices.MasterOrderId=CLOI_ClientOrderItems.MasterOrderId
where
  datepart(mm,in_date_issued)=2
and
  datepart(yyyy,in_date_issued)=2014
group by
  cl_id

select
  sum(in_total)
from
  IN_Invoices
where
  datepart(mm,in_date_issued)=2
and
  datepart(yyyy,in_date_issued)=2014

从这个查询我得到in_total的结果并使用这个查询我需要显示cl_id和count(order)

1 个答案:

答案 0 :(得分:0)

您可以将其添加到SELECT中,假设您正在查找每个cl_id的总计。否则,您需要将cl_id添加到第二个查询并像第一个示例中那样执行INNER JOIN。

DECLARE @param1 integer = 2
DECLARE @param2 integer = 2014

select
dbo.CLOI_ClientOrderItems.cl_id,
count(dbo.IN_Invoices.MasterOrderId) as Orders,
sum(dbo.IN_Invoices.in_total) as Total,
OverallTotal = (select sum(in_total) from IN_Invoices where datepart(mm,in_date_issued)=@param1 and datepart(yyyy,in_date_issued)=@param2)
from
 IN_Invoices
inner join
 CLOI_ClientOrderItems
on
 IN_Invoices.MasterOrderId=CLOI_ClientOrderItems.MasterOrderId
where
 datepart(mm,in_date_issued)=@param1
and
 datepart(yyyy,in_date_issued)=@param2
group by
 cl_id