将sql中两列之间的值相乘

时间:2015-02-11 10:17:40

标签: sql sql-server

我的查询

SELECT  DATEDIFF(day,SD.STARTDATE,SD.ENDDATE) AS TotalDays ,amount 
FROM staydetails 

例如,金额列的值可能为100,我需要将totaldaysamount的值相乘,然后将结果添加到另一列。

3 个答案:

答案 0 :(得分:1)

只需将计算列添加到选择列表中,如下所示:

 select  
 DATEDIFF(day,SD.STARTDATE,SD.ENDDATE) AS TotalDays ,
 amount,
 (DATEDIFF(day,SD.STARTDATE,SD.ENDDATE) * amount) AS CalculatedAmount
from staydetails

请注意,您需要重复DATEDIFF功能 - 您不能使用别名TotalDays。

答案 1 :(得分:0)

非常直接:

select  DATEDIFF(day,SD.STARTDATE,SD.ENDDATE) AS TotalDays ,amount,
        (DATEDIFF(day,SD.STARTDATE,SD.ENDDATE) * amount) as Result 
from staydetails 

答案 2 :(得分:0)

只需将它们相乘:

select  DATEDIFF(day,SD.STARTDATE,SD.ENDDATE) AS TotalDays ,
        amount ,
        DATEDIFF(day,SD.STARTDATE,SD.ENDDATE) * amount AS CalculatedValue
from staydetails

您可能尝试过这样引用TotalDaysTotalDays * amount,但您必须对基础值执行计算,这是DATEDIFF计算的结果,而不是别名列名。