-3

在此处输入图像描述

如何使用屏幕截图表获取每个产品代码的期初余额和期末余额。sql server 2008。
从截图来看,产品代码1已经发布了两次,最后余额反映了当前余额....我需要获取所有产品代码的最后余额。

  select TOP 1 Balance as OpeningBalance 
  from StockTransfer where ProductCode = 1 and TransferType = 'Product' 
  and TransactionDate between '2013-03-17' and '2013-03-22' 

  select TOP 1 Balance as ClosingBalance 
  from StockTransfer where ProductCode = 1 and TransferType = 'Product' 
  and TransactionDate between '2013-03-17' and '2013-03-22' 
  order by TransactionDate desc 

但这仅适用于一种产品。

4

3 回答 3

2

尝试:

with cte as
(select s.*,
        row_number() over (partition by ProductCode 
                           order by TransactionDate) ra,
        row_number() over (partition by ProductCode 
                           order by TransactionDate desc) rd
 from StockTransfer
 where TransferType = 'Product' and 
       TransactionDate between '2013-03-17' and '2013-03-22')
select ProductCode,
       max(case ra when 1 then Balance end) OpeningBalance,
       max(case rd when 1 then Balance end) ClosingBalance
from cte
group by ProductCode
于 2013-07-19T09:34:16.093 回答
0

根据上面的评论 - 很高兴以文本格式提供您的查询,因此不必重新输入。

现在,要解决您的问题,您需要使用相关子查询。我相信所有 SQL 数据库引擎都支持它们。请参阅Wikipedia - 这是一个很好的起点。

于 2013-07-19T09:27:28.993 回答
0

尝试这个

SELECT
  (select TOP 1 Balance as OpeningBalance 
   from StockTransfer 
   where ProductCode = ST.ProductCode and TransferType = 'Product' 
   and TransactionDate between '2013-03-17' and '2013-03-22' 
  ) As opening balance,

  (select TOP 1 Balance as ClosingBalance 
   from StockTransfer 
   where ProductCode = ST.ProductCode and TransferType = 'Product' 
   and TransactionDate between '2013-03-17' and '2013-03-22' 
   order by TransactionDate desc
   ) as colosing balance

FROM 
 StockTransfer  ST 
WHERE  TransactionDate between '2013-03-17' and '2013-03-22' 

GROUP BY ProductCode 

这将为整个产品返回相同的结果

于 2013-07-19T09:30:48.383 回答