简体   繁体   中英

MySQL: How to add the result of two fields created in the current select statement?

I am creating a MySQL View table, so my code looks something like this so far:

CREATE VIEW `myview`
AS SELECT
    (do some stuff here) AS `Revenue1`,
    (do some more here)  AS `Revenue2`
FROM ...

Now I want to add a column that is the sum of both of those fields, so I tried this:

CREATE VIEW `myview`
AS SELECT
    (do some stuff here) AS `Revenue1`,
    (do some more here)  AS `Revenue2`,
    (`Revenue1` + `Revenue2`) AS `TotalRevenue`
FROM ...

but this resulted in an error saying that the Revenue1 field was unknown. How can I add the two fields and get the result as a new column?

I think this should work:

CREATE VIEW `myview` 
AS 
  SELECT 
       (do some stuff here) AS `Revenue1`,     
       (do some more here)  AS `Revenue2`,     
       (do some stuff here) + (do some more here) AS `TotalRevenue`
  FROM ... 

you must repeat the stuff as:

CREATE VIEW `myview`
AS SELECT
    (do some stuff here) AS `Revenue1`,
    (do some more here)  AS `Revenue2`,
    ((do some stuff here) + (do some more here)) AS `TotalRevenue`
FROM ...

or create a second view as:

CREATE VIEW `myview_Two`
AS SELECT
    `Revenue1`,
    `Revenue2`,
    `Revenue1` + `Revenue2` AS `TotalRevenue`
FROM myview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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