Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This SQL statement seems to get what you want (t is the table name of the sampe table):</p> <pre><code>SELECT d.id, d.duration, d.duration - IFNULL( ( SELECT Sum( timestampdiff( SQL_TSI_DAY, no_hold.d2, ( SELECT min(d1) FROM t t4 WHERE t4.id = no_hold.id and t4.d1 &gt; no_hold.d2 ))) FROM ( SELECT DISTINCT id, d2 FROM t t1 WHERE ( SELECT sum( IIF( t1.d2 between t2.d1 and t2.d2, 1, 0 ) ) FROM t t2 WHERE t2.id = t1.id and t2.d2 &lt;&gt; t1.d2 ) = 0 And d2 &lt;&gt; ( select max( d2 ) from t t3 where t3.id = t1.id )) no_hold WHERE no_hold.id = d.id ), 0 ) "parts hold" FROM ( SELECT id, timestampdiff( SQL_TSI_DAY, min( d1 ), max( d2 ) ) duration FROM t GROUP BY id ) d </code></pre> <p>The outer query gets the duration of the repair work. The complex subquery calculates the total number of days not waiting for parts. This is done by locating the start dates where the vehicle is not waiting for parts, and then count the number of days until it begins to wait for parts again:</p> <pre><code>// 1) The query for finding the starting dates when the vehicle is not waiting for parts, // i.e. finding all d2 that is not within any date range where the vehicle is waiting for part. // The DISTINCT is needed to removed duplicate starting "no hold" period. SELECT DISTINCT id, d2 FROM t t1 WHERE ( SELECT sum( IIF( t1.d2 between t2.d1 and t2.d2, 1, 0 ) ) from t t2 WHERE t2.id = t1.id and t2.d2 &lt;&gt; t1.d2 ) = 0 AND d2 &lt;&gt; ( SELECT max( d2 ) FROM t t3 WHERE t3.id = t1.id ) ) </code></pre> <p>// 2) The days where it vehicle is not waiting for part is the date from the above query till the vehicle is // waiting for part again</p> <pre><code>timestampdiff( SQL_TSI_DAY, no_hold.d2, ( SELECT min(d1) FROM t t4 WHERE t4.id = no_hold.id and t4.d1 &gt; no_hold.d2 ) ) </code></pre> <p>Combining the two above and aggregating all such periods gives the number of days that the vehicle is not waiting for parts. The final query adds an extra condition to calculate result for each id from the outer query.</p> <p>This probably is not terribly efficient on very large table with many ids. It should fine if the id is limited to one or just a few.</p>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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