我一直收到这个错误 专栏' vStockSerialsTemp.Id'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。 ALTER VIEW vStockSerials
SELECT Id
, StockOid
, WarehouseOid
, serial
, StockCode
, ActionPrice
, StockName
, StockTitle
, Warehouse
, SlipDate
, ActionType
, SlipType
FROM vStockSerialsTemp
UNION ALL
SELECT Id
, StockOid
, WarehouseOid
, serial
, StockCode
, sum(CASE WHEN ActionType = 'Income' THEN ActionPrice ELSE -ActionPrice END) as ActionPrice
, StockName
, StockTitle
, Warehouse
, SlipDate
, SlipType
, 'Balance' as ActionType
FROM vStockSerialsTemp
GROUP BY
serial
HAVING sum(CASE WHEN ActionType = 'Expense' THEN ActionPrice ELSE -ActionPrice END) <> 0
--ORDER BY
-- ActionType DESC
GO
答案 0 :(得分:1)
在您汇总UNION ALL
的{{1}}的第二个查询中,您需要在其他字段ActionPrice
上GROUP BY
,因为这不是来自的ActionType
字段表):
SELECT Id,StockOid,WarehouseOid,serial,StockCode,ActionPrice,StockName,
StockTitle,Warehouse,SlipDate,ActionType,SlipType
FROM
vStockSerialsTemp
UNION ALL
SELECT
Id,StockOid,WarehouseOid,serial,StockCode,
sum(CASE WHEN ActionType = 'Income'
THEN ActionPrice ELSE -ActionPrice END) as ActionPrice,
StockName,StockTitle,Warehouse,SlipDate,SlipType,
'Balance' as ActionType
FROM
vStockSerialsTemp
GROUP BY
Id,StockOid,WarehouseOid,serial,StockCode,StockName,StockTitle,Warehouse,
SlipDate,SlipType
HAVING
sum(CASE WHEN ActionType = 'Expense'
THEN ActionPrice ELSE -ActionPrice END) <> 0
答案 1 :(得分:0)
您只能使用分区“串行”聚合:
SELECT Id,StockOid,WarehouseOid,serial,StockCode,ActionPrice,StockName,StockTitle,Warehouse,SlipDate,ActionType,SlipType
FROM
vStockSerialsTemp
UNION ALL
SELECT * from
(SELECT
Id,StockOid,WarehouseOid,serial,StockCode,
sum(CASE WHEN ActionType = 'Income' THEN ActionPrice ELSE -ActionPrice END) OVER(PARTITION BY serial) as ActionPrice,
StockName,StockTitle,Warehouse,SlipDate,SlipType,
'Balance' as ActionType) x WHERE ActionPrice<>0
--ORDER BY
-- ActionType DESC
GO