Note that there are some explanatory texts on larger screens.

plurals
  1. POUse previous value in MySQL to compute the next field?
    primarykey
    data
    text
    <p>How to use previous values in MySQL to compute the next value? I couldn't explain what I mean more clearly in my poor English (anyone can understand what I asked by seeing the title of this post?), so let me explain it in a snippet:</p> <pre><code> select year_id, sum(case when event_cd >= 20 then 1 else 0 end) as h, sum(case when ab_fl = "T" then 1 else 0 end) as ab, h/ab as ba from events group by year_id </code></pre> <p>in the above snippet, when you run the query you will get the error, since there are no such columns in <code>events</code> table as <code>h</code> or <code>ab</code>. However, I want to use <code>h</code> and <code>ab</code> which are computed in the previous <code>sum(case when ~)</code> syntax. I remember there are some sort of ways to make it possible, but I don't remember how to do nor as I said, I couldn't find any relevant posts to meet what I'm asking due to my poor English, though since I'm sure this question is already posted here at SO, it's quite helpful even if you just link it with no detailed explanation.</p> <p>Thanks.</p> <p>[Update]</p> <p>Thanks for the answers. I just wanted to use previous values in order to avoid subqueries and hence lots of redundant typing, and make the entire code more readable. I've used either methods (subqueries or write the entire syntax twice just to compute another value) as described by Mosty Mostacho, and if this is not feasible or pretty risky to use in MySQL, I can surely accept those two methods above. Sorry for the confusion.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload