To get submission's statistics on a given element of a webform I'm using the following query.

public function getElementSubmissionsStatistics($elementID): array {
    $db = \Drupal::database();
    $query = $db->select('webform_submission_data', 'wsd');
    $query->fields('wsd', ['value', 'name']);
    $query->addExpression('COUNT(value)', 'quantity');
    $query->condition('wsd.webform_id', $this->webform->id());
    $query->condition('name', $elementID);
    $query->groupBy('wsd.value');
    $records = (array) $query->execute()->fetchAllAssoc('value');

    $values = [];

    $totalQuantity = (int) array_sum(array_column($records,'quantity'));;

    foreach ($records as $key => $record) {
      $values[$key]['quantity'] = (int) $record->quantity;
      $values[$key]['percentage'] = (float) $record->quantity / $totalQuantity;
      $values[$key]['value'] = (string) $record->value;
    }
 
    $this->elementsStatistics[$elementID] = $values;
    return $this->elementsStatistics[$elementID];

}

I'm using this on radio element (but should works on any element) to count the number of time an option was selected.

It work well but I wanted to add some condition to filter my query on other webform's field values. Webform query seem to greatly simplify this. But if I'm not mistaken it doesn't provide a way to group_by and count.

I need to load all the submission and do this in PHP? Or is they another option?

Would it be possible to support COUNT and groupBy in the future?

Comments

gagarine created an issue. See original summary.

imclean’s picture

Version: 8.x-2.0-alpha2 » 8.x-1.x-dev

8.x-2.0 was a mistake, the current branch is 8.x-1.x.