我想问一下如何将这两个查询组合成一个子查询?
select c.CustomerName, A.Qty
from Customer c join (select s.CustomerID, pd.Date, s.Qty
from Period pd join Sales s on pd.TimeID = s.TimeID) A on c.CustomerID = A.CustomerID
where @Date = A.Date
和
select sum(case when (pd.Date between '2010-03-15' and @Date) then s.Qty else 0 end) as TotalQty
from Period pd full join Sales s on pd.TimeID = s.TimeID full join Customer c on s.CustomerID = c.CustomerID
group by c.CustomerName, c.CustomerID
它们应该导致一个表包含以下列:CustomerName,Qty和TotalQty。我尝试了很多方法,但根本没用。真的希望你的帮助,谢谢。
答案 0 :(得分:0)
回答您的问题,假设您将结果视为一行而不是“列”:
select c.CustomerName, A.Qty,(select sum(case when (pd.Date between '2010-03-15' and @Date) then s.Qty else 0 end)
from Period pd full join Sales s on pd.TimeID = s.TimeID full join Customer c on s.CustomerID = c.CustomerID
group by c.CustomerName, c.CustomerID
) as TotalQty
from Customer c join (select s.CustomerID, pd.Date, s.Qty
from Period pd join Sales s on pd.TimeID = s.TimeID) A on c.CustomerID = A.CustomerID
where @Date = A.Date
如果您仍希望将结果作为单个列,请将“行到列转置”