Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I would use an aggregate function with a CASE expression to convert the <code>old</code> and <code>new</code> values into columns, then you can easily get the <code>total</code> and <code>average</code> using <code>sum()</code> and <code>avg()</code>:</p> <pre><code>select [procedure], SUM(case when proc_old_new = 'Old' then proc_time else 0 end) Old, SUM(case when proc_old_new = 'New' then proc_time else 0 end) New, SUM(proc_time*1.0) Total, sum(proc_time*1.0)/2 [avg] from mytable group by [procedure]; </code></pre> <p>See <a href="http://sqlfiddle.com/#!3/57e0e0/1" rel="nofollow">SQL Fiddle with Demo</a>. This gives a result:</p> <pre><code>+-----------+-----+-----+-------+----------+ | procedure | Old | New | Total | avg | +-----------+-----+-----+-------+----------+ | Proc1 | 3 | 2 | 5.0 | 2.500000 | | Proc2 | 8 | 0 | 8.0 | 4.000000 | | Proc3 | 4 | 14 | 18.0 | 9.000000 | +-----------+-----+-----+-------+----------+ </code></pre> <p>You desired result is not exactly clear but if you want to only average based on whether the <code>old</code>/<code>new</code> value is not null, then you could also use:</p> <pre><code>;with cte as ( select [procedure], sum(case when proc_old_new = 'Old' then proc_time end) Old, sum(case when proc_old_new = 'New' then proc_time end) New from mytable group by [procedure] ) select [procedure], Old, New, coalesce(Old, 0) + coalesce(New, 0) Total, AVG(value) [avg] from cte cross apply ( select cast(old as decimal(10, 2)) union all select cast(new as decimal(10, 2)) ) c(value) group by [procedure], Old, New </code></pre> <p>See <a href="http://sqlfiddle.com/#!3/57e0e0/2" rel="nofollow">SQL Fiddle with Demo</a>. This version gives a result:</p> <pre><code>+-----------+-----+------+-------+----------+ | procedure | Old | New | Total | avg | +-----------+-----+------+-------+----------+ | Proc1 | 3 | 2 | 5 | 2.500000 | | Proc2 | 8 | NULL | 8 | 8.000000 | | Proc3 | 4 | 14 | 18 | 9.000000 | +-----------+-----+------+-------+----------+ </code></pre>
    singulars
    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.
    1. VO
      singulars
      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