我必须尽快解决这个问题,但我是Transact-SQL
的新手。
我有一个观点vStockSerialsTemp
:
Serial StockCode ActionPrice StockName Warehouse ActionType
123 P-0304 350 Galaxy S4 Centeral Income
456 P-0305 450 Iphone 5s Centeral Income
567 P-0305 450 Iphone 5s Centeral Income
123 P-0304 350 Galaxy S4 Centeral Expense
235 P-0304 350 Galaxy S4 Centeral Income
567 P-0305 450 Iphone 5s Centeral Expense
所以,基于这个观点,我必须创建一个新的View,它将使用相同的Serials计算每个股票的余额。我们用ActionType减去行 具有相同序列的ActionType收入的费用。因此,视图应如下所示:
Serial StockCode ActionPrice StockName Warehouse ActionType
123 P-0304 350 Galaxy S4 Centeral Income
456 P-0305 450 Iphone 5s Centeral Income
567 P-0305 450 Iphone 5s Centeral Income
123 P-0304 350 Galaxy S4 Centeral Expense
235 P-0304 350 Galaxy S4 Centeral Income
567 P-0305 450 Iphone 5s Centeral Expense
-----------------------------------------------------------------
456 P-0305 450 Iphone 5s Centeral Balance
235 P-0304 350 Galaxy S4 Centeral Balance
CREATE vStockSerials as
SELECT * FROM [dbo].[dbo.vStockSerialsTemp]
UNION
// Here is the problem indeed
如何从vStockSerialsTemp
选择行?
答案 0 :(得分:1)
我不知道这是不是最好的方法。但你可以这样做:
SELECT
vStockSerialsTemp.Serial,
vStockSerialsTemp.StockCode,
vStockSerialsTemp.ActionPrice,
vStockSerialsTemp.StockName,
vStockSerialsTemp.Warehouse,
vStockSerialsTemp.ActionType
FROM
vStockSerialsTemp
UNION
SELECT
vStockSerialsTemp.Serial,
vStockSerialsTemp.StockCode,
vStockSerialsTemp.ActionPrice,
vStockSerialsTemp.StockName,
vStockSerialsTemp.Warehouse,
(
CASE vStockSerialsTemp.ActionType
WHEN 'Income'
THEN 'Expense'
ELSE 'Income'
END
)AS ActionType
FROM
vStockSerialsTemp
答案 1 :(得分:1)
SELECT Serial, StockCode, ActionPrice, StockName, Warehouse
FROM [dbo].[dbo.vStockSerialsTemp] Where ActionType = 'INCOME'
EXCEPT
SELECT Serial, StockCode, ActionPrice, StockName, Warehouse
FROM [dbo].[dbo.vStockSerialsTemp] Where ActionType = 'EXPENSE'
我希望它会奏效。你可以申请点票。要将数据并排打印google for Derived table或CTE
答案 2 :(得分:1)
结合后的这样的东西:
select a.Serial, a.StockCode, (a.ActionPrice - b.ActionPrice) as ActionPrice,
a.StockName, a.Warehouse, 'Balance' as ActionType
from [dbo].[dbo.vStockSerialsTemp] a
inner join [dbo].[dbo.vStockSerialsTemp] b
on a.Serial = b.Serial
and a.ActionType = 'Income'
and b.ActionType = 'Expense'
将相同的视图加入到自身中。一个有所有费用,另一个有所有收入。
答案 3 :(得分:1)
根据您的预期结果,我假设您不希望显示余额为零的连续出版物的数据。
SELECT
Serial,
StockCode,
ActionPrice,
StockName,
Warehouse,
ActionType
FROM
vStockSerialsTemp
UNION ALL
SELECT
Serial,
StockCode,
sum(CASE WHEN ActionType = 'Income' THEN ActionPrice ELSE -ActionPrice END),
StockName,
Warehouse,
'Balance'
FROM
vStockSerialsTemp
GROUP BY
Serial,
StockCode,
StockName,
Warehouse
HAVING
sum(CASE WHEN ActionType = 'Income' THEN ActionPrice ELSE -ActionPrice END) <> 0
ORDER BY
ActionType DESC