我有一个database table
与name
,address
和monthly account expense
作为每个月的列信息。
我想将month1
的费用添加到month12
表的accounts
数据,但它是varchar
数据类型,我想将其转换为float
数据类型,并在查询中使用逻辑表达式获取所有费用的SUM
(month 1
) + month 2
+ ... month12
)应该大于10,000
。
但我无法解决此问题,因为查询无法正常工作并且出现错误
请检查此查询,并告知我任何更改
SELECT name ,address ,CAST(([month1] + [month2]...[month12] AS float) AS 'total expense' FROM Accounts_Table WHERE name LIKE 'a%' GROUP BY name, address, 'total expense' HAVING 'total expense' > 10000
一些指针将很好地解决这个问题。
添加和转换month
列的方式不正确。
此外,您将无法在[Total Expense]
子句中在您声明它的同一查询中调用HAVING
的别名。使用SUBQUERY
。
见下文。
SELECT [name] ,[address] ,[Total Expense] FROM ( SELECT [name] ,[address] ,CAST([month1] AS float) + CAST([month2] AS float) + CAST([month3] AS float) + CAST([month4] AS float) + CAST([month5] AS float) + CAST([month6] AS float) + CAST([month7] AS float) + CAST([month8] AS float) + CAST([month9] AS float) + CAST([month10] AS float) + CAST([month11] AS float) + CAST([month12] AS float) AS [Total Expense] FROM [Accounts_Table] WHERE [name] LIKE 'a%') AS [src] GROUP BY [name] ,[address] ,[Total Expense] HAVING [Total Expense] > 10000
您必须在添加之前将每个varchar列转换为Float。看看解释
, (CAST( [month1] as float) + CAST([month2] as float)... CAST([month12] as Float)) AS
'total expense'