我的查询设置如下,但结果不像我想要的
SELECT * INTO #Temp FROM (SELECT Product,PeriodNum,OpenBal,Month Qty,0 as OnHandQty
FROM StockTransaction
WHERE Company = 1 AND
FiscalYear = 2016 AND
DeptCode = 'phst' and
Product = 'Product A' and
PeriodNum between 1 and 10) A
SELECT * INTO #Temp2 FROM (SELECT Product,PeriodNum,OpenBal,Month Qty,OnHandQty
FROM StockTransaction
WHERE Company = 1 AND
FiscalYear = 2016 AND
DeptCode = 'phst' and
Product = 'Product A' and
PeriodNum between 1 and 10 and
PeriodNum = (SELECT max(PeriodNum)
from StockTransaction s
WHERE s.DeptCode = StockTransaction.DeptCode and
s.ItemCode = StockTransaction.ItemCode)) C
SELECT * INTO #Temp3 FROM (C.Product,C.PeriodNum,C.OpenBal,C.Month Qty,C.OnHandQty
FROM #Temp2 C INNER JOIN
#Temp T ON C.DeptCode = T.DeptCode and
C.ItemCode = T.ItemCode and
C.PeriodNum = T.PeriodNum) as E
SELECT * INTO #Result FROM (SELECT * FROM #Temp
UNION ALL SELECT * FROM #Temp3) As result
SELECT * FROM #Result
你能帮助我如何操纵我得到的数据???我只有数据显示像图片。如果从select statment获得5行数据, OpenBal 值仅显示最小 PeriodNum , OnHandQty 值仅显示最大 PeriodNum
答案 0 :(得分:0)
我没有看到一种直观的方式来做到这一点。
因此,假设您需要每个产品的数据,它可能会像这样。
SELECT * INTO #Temp FROM (SELECT Product,PeriodNum,0 as OpenBal,Month Qty,OnHandQty
FROM StockTransaction
WHERE Company = 1 AND
FiscalYear = 2016 AND
DeptCode = 'phst' and
Product = 'Product A' and
PeriodNum between 1 and 10 and
(Product, PeriodNum) IN (SELECT Product, max(PeriodNum)
from StockTransaction s group by Product)
SELECT * INTO #Temp2 FROM (SELECT Product,PeriodNum,OpenBal,Month Qty,0 as OnHandQty
FROM StockTransaction
WHERE Company = 1 AND
FiscalYear = 2016 AND
DeptCode = 'phst' and
Product = 'Product A' and
PeriodNum between 1 and 10 and
(Product, PeriodNum) IN (SELECT Product, min(PeriodNum)
from StockTransaction s group by Product)
SELECT * INTO #Temp3 FROM (SELECT Product,PeriodNum,0 as OpenBal,Month Qty,0 as OnHandQty
FROM StockTransaction
WHERE Company = 1 AND
FiscalYear = 2016 AND
DeptCode = 'phst' and
Product = 'Product A' and
PeriodNum between 1 and 10 and
(Product, PeriodNum) NOT IN (SELECT Product, PeriodNum
from #temp1 UNION SELECT Product, PeriodNum from #temp2)
SELECT * INTO #Result FROM (SELECT * FROM #Temp
UNION SELECT * FROM #Temp2 UNION SELECT * FROM Temp3) As result
SELECT * FROM #Result