在 SQL 中通过 cast 函数转换多行
Converting multiple rows through cast function in SQL
我有一个 database table
,其中 name
、address
和 monthly account expense
作为每个月的列信息。
我想添加 month1
到 month12
数据的 accounts
table 但它是 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
列的方式不正确。
此外,您将无法在声明它的同一查询的 HAVING
子句中调用 [Total Expense]
的别名。使用 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'
我有一个 database table
,其中 name
、address
和 monthly account expense
作为每个月的列信息。
我想添加 month1
到 month12
数据的 accounts
table 但它是 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
列的方式不正确。
此外,您将无法在声明它的同一查询的 HAVING
子句中调用 [Total Expense]
的别名。使用 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'