Note that there are some explanatory texts on larger screens.

plurals
  1. POSeparating/Sorting single column values into several columns using case function
    primarykey
    data
    text
    <p>I have two tables that I want to join and split with a case function depending on the values in one of the columns. (I know, sounds weird so let me explain)</p> <p>It's a process where I run separate batches. Every batch has several samples that are measured in instances of voltage readings in several locations. My two tables looks like this:</p> <pre><code>Sample Readings id id BatchesID SampleID ... voltage ... location </code></pre> <p>When a batch is run, it takes one sample at a time and for every location (25 locations) it takes about 20 readings of the voltage before moving on to the next one.</p> <p>I want to look at one batch at a time, and for every Sample.id, I want to gather the AVG(voltage) for all the locations. My table for Readings turns out like:</p> <pre><code>SampleID location voltage 1 1 5.23 1 1 4.53 ... ... ... 1 25 7.89 2 1 4.96 2 1 5.04 ... ... ... 2 25 6.09 ... </code></pre> <p>But I want it to look like:</p> <pre><code>SampleID avg_v_for_1 avg_v_for_2 ... avg_v_for_25 1 4.73 5.24 ... 6.35 2 3.87 4.76 ... 9.32 ... ... ... ... ... 200 6.73 3.87 ... 8.23 </code></pre> <p>Basically, what I want to do is for every separate sample, I want to take the average voltage for all the measurements in every location and put in on a single row. What my current syntax looks like is this:</p> <pre class="lang-MySQL prettyprint-override"><code>SELECT Readings.SampleID, Sample.BatchesID (case when location = '1' then AVG(voltage) else 0 end) avg_v_for_1, (case when location = '2' then AVG(voltage) else 0 end) avg_v_for_2, ... (case when location = '25' then AVG(voltage) else 0 end) avg_v_for_25 FROM DB.Readings INNER JOIN Sample ON Readings.SampleID = Sample.id WHERE Sample.BatchesID = 'specific_batch_id' GROUP BY Readings.location, Sample.id; </code></pre> <p>The problem is that this generates the following table:</p> <pre><code>SampleID avg_v_for_1 avg_v_for_2 ... avg_v_for_25 1 4.73 0 ... 0 1 0 4.76 ... 0 1 0 0 ... 6.73 2 3.87 0 ... 0 2 0 4.83 ... 0 ... </code></pre> <p>How can I get MySQL to gather ALL the average values for EVERY location on a SINGLE row? I have tried removing the group by location and only group by sampleID but then I only get the values for the first location and everything else becomes 0.</p> <p>Any help is appreciated, thank you!</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.
 

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