Search code examples
phpmysqlsumrollup

mysql sum totals without using with rollup


I am using phpgrid to display query data, then filtering through form select on page. This works fine until I add with rollup to the query to sum columns and I wondered if there is any other method of summing these columns (12 of them)?

This doesn't work telling me Couldn't execute query. Unknown column 'i.signedupdate' in 'where clause

SELECT * FROM
  (SELECT IFNULL(c.Adviser, 'GRAND TOTAL') AS Adviser,
  Sum(Month(i.SignedUpDate) = 1) As Jan,
  Sum(Month(i.SignedUpDate) = 2) As Feb,
  Sum(Month(i.SignedUpDate) = 3) As Mar,
  Sum(Month(i.SignedUpDate) = 4) As Apr,
  Sum(Month(i.SignedUpDate) = 5) As May,
  Sum(Month(i.SignedUpDate) = 6) As Jun,
  Sum(Month(i.SignedUpDate) = 7) As Jul,
  Sum(Month(i.SignedUpDate) = 8) As Aug,
  Sum(Month(i.SignedUpDate) = 9) As Sept,
  Sum(Month(i.SignedUpDate) = 10) As Oct,
  Sum(Month(i.SignedUpDate) = 11) As Nov,
  Sum(Month(i.SignedUpDate) = 12) As Dece,
  i.id,
  Count(i.id) As Total
    From
  tbl_lead i Inner Join
  tbl_clients c On i.client_id = c.client_id
Group By
    c.Adviser with rollup) As t

This works, I can select years ok but no column summary

SELECT * FROM
  c.Adviser AS Adviser,
  Sum(Month(i.SignedUpDate) = 1) As Jan,
  Sum(Month(i.SignedUpDate) = 2) As Feb,
  Sum(Month(i.SignedUpDate) = 3) As Mar,
  Sum(Month(i.SignedUpDate) = 4) As Apr,
  Sum(Month(i.SignedUpDate) = 5) As May,
  Sum(Month(i.SignedUpDate) = 6) As Jun,
  Sum(Month(i.SignedUpDate) = 7) As Jul,
  Sum(Month(i.SignedUpDate) = 8) As Aug,
  Sum(Month(i.SignedUpDate) = 9) As Sept,
  Sum(Month(i.SignedUpDate) = 10) As Oct,
  Sum(Month(i.SignedUpDate) = 11) As Nov,
  Sum(Month(i.SignedUpDate) = 12) As Dece,
  i.id,
  Count(i.id) As Total
    From
  tbl_lead i Inner Join
  tbl_clients c On i.client_id = c.client_id
Group By
    c.Adviser

If I simply remove the subquery and leave 'with rollup' it alerts me of incorrect use of order by & with rollup?

Any ideas much appreciated, just need to sum all those columns


Solution

  • You should use a SQL view as recommended here.

    It's recommended to use a Sql view when the Sql is complex. It's essentially a virtual table, of which that is defined as a SQL SELECT query with joins. Because a database view is similar to a database table, which consists of rows and columns, so you can query data against like an actual database table.

    Another benefit is that you can then reuse this view. Additionally, if you use a view instead of a joined tables, in the future if you need to change a column, you can easily do that and only require changes to the Sql view.