简体   繁体   English

如何在 SQL 中使用 cast 进行多列选择?

[英]How can I use cast in SQL with multiple column selections?

I tried this to get our revenue:我试过这个来获得我们的收入:

SELECT 
    CAST(stays_in_week_nights AS int) + 
        CAST(stays_in_weekend_nights AS int) * 
        CAST(adr AS int) AS revenue
FROM 
    Hotels

I expected to get a number as the result of the calculation - but instead, I get this error:我希望得到一个数字作为计算结果 - 但相反,我得到了这个错误:

Msg 245, Level 16, State 1, Line 2消息 245,级别 16,状态 1,第 2 行
Conversion failed when converting the varchar value '111.6' to data type int.将 varchar 值“111.6”转换为数据类型 int 时转换失败。

cast is as a decimal instead of as an int. cast 是小数而不是 int。 Assuming it is the adr field that is the problem, it would be假设是问题所在的 adr 字段,它将是

SELECT CAST(stays_in_week_nights AS int) + CAST(stays_in_weekend_nights AS int) * CAST(adr AS decimal(10,2)) AS revenue
FROM Hotels

What you would need for the two parameters in decimal(10,2) would depend on your data. decimal(10,2) 中的两个参数需要什么取决于您的数据。 Decimal(10,2) would give you 8 places before the decimal point and 2 after. Decimal(10,2) 会给你小数点前 8 位和小数点后 2 位。

Also, you may want to add an extra set of parentheses to make sure you are calculating it correctly.此外,您可能希望添加一组额外的括号以确保您计算正确。 Do you want (week+weekend) * adr or week + (weekend*adr)你想要 (week+weekend) * adr 还是 week + (weekend*adr)

What you are currently going to get is the second.你目前要得到的是第二个。 Even if that is what you want, adding parentheses would clarify to the next developer that that is what you intended to do即使那是你想要的,添加括号也会向下一个开发人员澄清这就是你打算做的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM