0

I'm trying to count/group by for 25 columns in a table. I have success counting one column at a time using ...

//COUNT OFF
$sql = "SELECT count(q1) as count, q1 FROM results GROUP BY q1";
$stmt = $db->prepare($sql);
$stmt->execute();
$firstResults = $stmt->fetchAll();

$sql = "SELECT count(q2) as count, q2 FROM results GROUP BY q2";
$stmt = $db->prepare($sql);
$stmt->execute();
$secondResults = $stmt->fetchAll();

$sql = "SELECT count(q3) as count, q3 FROM results GROUP BY q3";
$stmt = $db->prepare($sql);
$stmt->execute();
$thirdResults = $stmt->fetchAll();

$firstResults = json_encode($firstResults); 
$secondResults = json_encode($secondResults);
$thirdResults = json_encode($thirdResults);

..and that works fine for a few columns. It seems like there should be a less-repetitive way to do the same for 25 columns in the same table. Where would I start?

Layne
  • 642
  • 1
  • 13
  • 32
  • Sorry, edited original to reflect multiple columns, not tables. – Layne Jun 18 '15 at 15:30
  • 2
    so, have you tried `COUNT(*)`? then do a `GROUP BY` for the columns you want. It accepts comma-seperated values. `GROUP BY a, b` - `SELECT a, b, COUNT(a) FROM tbl GROUP BY a, b` type of thing. or the `*` as I indicated. As pulled from http://stackoverflow.com/q/10380990/ – Funk Forty Niner Jun 18 '15 at 15:35
  • ...and using aliases. I didn't have time to edit my comment above to include that. Here's an example http://stackoverflow.com/a/18466328/ and http://stackoverflow.com/a/2068711/ – Funk Forty Niner Jun 18 '15 at 15:41

0 Answers0