Skip to content
Advertisement

Mysql Select group by and without group by in one query

How can I select group by and without group by in one select query? I have a query like this

SELECT date, sum(total) as quotation_total
  FROM suspended_bills 
 WHERE type='quotation'
 GROUP BY YEAR(date), MONTH(date)

Here it is taking a group by year and month but I want a sum(total) without group by year and month. So I am able to get full sum(total) without a division of month and year.

This is not a duplicate entry as rollup is generating extra rows that I dont need, I only need the total of sum, so when I run this query with rollup it gave me more rows that is not desired. So all is wrong with roll up query.

Advertisement

Answer

In MySQL, the easiest way is a join or subquery:

select YEAR(sb.date), MONTH(sb.date), sum(sb.total) as quotation_total,
       t.total_total
from suspended_bills sb cross join
      (select sum(total) as total_totla
       from suspended_bills
       where type = 'quotation'
      ) t
where sb.type = 'quotation'
group by YEAR(sb.date), MONTH(sb.date), t.total_total;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement