-1

请问如何将这两个查询合并为一个子查询?

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。我尝试了很多方法,但它们根本不起作用。真心希望得到您的帮助,谢谢。

4

1 回答 1

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

如果您仍希望将结果作为单列,请谷歌“行到列转置”

于 2013-11-10T09:45:53.020 回答