0

I have a database table with name, address, and monthly account expense as column information for every single month.

I want to add expenses from month1 to month12 data of an accounts table but it is in varchar data type, I want to convert it into float data type and also use a logical expression in the query that gets the SUM of all the expenses (month 1 + month 2 +...month12) should be greater than 10,000.

But I am not able to solve this problem as the query is not working and am getting errors

Kindly check this query and let me know of any changes

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

Some pointers will be great to work around this problem.

4

2 回答 2

1

您添加和转换month列的方式不正确。

此外,您将无法在声明它的同一查询上调用子句中[Total Expense]的别名。HAVING使用SUBQUERY.

见下文。

选择 [名称]
      ,[地址]
      ,[总费用]
从 (
    选择 [名称]
          ,[地址]
          ,CAST([month1] AS 浮动) +
           CAST([month2] AS 浮动) +
           CAST([month3] AS 浮动) +
           CAST([month4] AS 浮动) +
           CAST([month5] AS 浮动) +
           CAST([month6] AS 浮动) +
           CAST([month7] AS 浮动) +
           CAST([month8] AS 浮动) +
           CAST([month9] AS 浮动) +
           CAST([month10] AS 浮动) +
           CAST([month11] AS 浮动) +
           CAST([month12] AS float) AS [总费用]
    FROM [Accounts_Table]
    WHERE [name] LIKE 'a%') AS [src]
按 [名称] 分组
        ,[地址]
        ,[总费用]
有 [总费用] > 10000
于 2018-09-11T03:07:08.013 回答
0

在添加之前,您必须将每个 varchar 列转换为 Float。看看解释

, (CAST( [month1] as float) + CAST([month2] as float)... CAST([month12] as Float))  AS 
   'total expense'
于 2018-09-11T05:29:57.363 回答