我有这个查询,
SELECT
ORDUNIQ ,
SUM(UNITPRICE * ORIGQTY) AS 'LineTotal',
SUM(TAMOUNT1 + TAMOUNT2 + TAMOUNT3 + TAMOUNT4 + TAMOUNT5) AS 'TotalTax',
CAST('LineTotal' as numeric(9,2)) as [lTotal],
CAST('TotalTax' as numeric(9,2)) as [tTax],
SUM('lTotal' + 'tTax') AS 'OverallTotal'
FROM OEORDD
Group BY ORDUNIQ
我正在尝试将'LineTotal'和'TotalTax'加在一起但是我收到以下错误
操作数数据类型varchar对sum运算符
无效
有谁能告诉我如何正确实现这一目标?
谢谢
贾斯汀
答案 0 :(得分:6)
; WITH taxCTE
AS
(
SELECT
ORDUNIQ
, SUM(UNITPRICE * ORIGQTY) AS 'LineTotal'
, SUM(TAMOUNT1 + TAMOUNT2 + TAMOUNT3 + TAMOUNT4 + TAMOUNT5) AS 'TotalTax'
FROM
OEORDD
GROUP BY
ORDUNIQ
)
SELECT
CAST(LineTotal AS NUMERIC(9, 2)) AS [lTotal]
, CAST(TotalTax AS NUMERIC(9, 2)) AS [tTax]
, SUM(CAST(LineTotal AS NUMERIC(9, 2)) + CAST(TotalTax AS NUMERIC(9, 2))) AS 'OverallTotal'
FROM
taxCTE ;
您无法像在原始查询中那样引用别名列。而是使用子查询,或者如上面的CTE。
答案 1 :(得分:5)
您无法在定义的同一级别引用列别名。因为您使用单引号分隔对象标识符,所以假设您正在尝试对字符串文字求和。
您可以将查询放入CTE以重用列别名和select
。
;WITH T AS
(
SELECT ORDUNIQ ,
SUM(UNITPRICE * ORIGQTY) AS LineTotal,
SUM(TAMOUNT1 + TAMOUNT2 + TAMOUNT3 + TAMOUNT4 + TAMOUNT5) AS TotalTax
FROM OEORDD
Group BY ORDUNIQ
)
SELECT *,
LineTotal + TotalTax AS OverallTotal
FROM T
答案 2 :(得分:0)
操作数数据类型varchar对sum运算符无效,这意味着您无法将varchar添加到整数。在sum语句中,所有列都应该是integer类型,none应该是varchar类型。所以我会检查你已经为初学者添加到sum语句中的每个列类型。