简体   繁体   English

SQL中的计算字段

[英]calculated field in SQL

I need to Add a field named "calc" that is calculated as 我需要添加一个名为“ calc”的字段,其计算公式为

if D.type_id = 1
then calc = calc + D.price
and if D.type_id = 2
then calc = clac - D.price      

what exactly should I add to the next SQL code to do that. 我到底应该添加什么到下一个SQL代码中呢?

SELECT T.type_name, D.*, I.name_inout
  FROM ((Type T
  INNER JOIN Daily D ON (T.type_id=D.type_id))
  INNER JOIN Incom I ON (I.id_inout=D.id_inout))
  WHERE D.today = DATE()
  Order by daily_id 

I really don't care about the field .. I just care about the final result of "calc" as I'll pass the final value to a Report. 我真的不在乎该字段..我只是在乎“计算”的最终结果,因为我会将最终值传递给报表。

If I'm reading the question correctly, you need a case statement. 如果我正确阅读了该问题,则需要一个案例说明。

SELECT 
    case D.type_id 
        when 1 then calc + D.price
        when 2 then calc - D.price
        else <<whatever your default is>>
    end as CalculatedPrice,
    T.type_name, D.*, I.name_inout
  FROM (
    (
        Type T
        INNER JOIN Daily D ON (T.type_id=D.type_id)
    )
  INNER JOIN Incom I ON (I.id_inout=D.id_inout))
  WHERE D.today = DATE()
  Order by daily_id 

If you want the SUM of the calculated prices using your formula, then you need a wrapped table as follows: 如果要使用公式计算得出的价格总和,则需要一个包装表,如下所示:

select sum(dtA.CalculatedPrice)
From (
  SELECT 
    case D.type_id 
        when 1 then calc + D.price
        when 2 then calc - D.price
        else <<whatever your default is>>
    end as CalculatedPrice,
    T.type_name, D.*, I.name_inout
  FROM (
    (
        Type T
        INNER JOIN Daily D ON (T.type_id=D.type_id)
    )
  INNER JOIN Incom I ON (I.id_inout=D.id_inout))
  WHERE D.today = DATE()
 ) dtA

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

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