Mysql – How to group the data in the following format

countgroup byMySQL

Using the following table


OrderDate     OrderID
[dates]       [id]

I want to display in the following format :

quater name   nooforders
q1            10
q2            10
q3            20

I have tried the following query :


select count(order_id)no_of_orders,
(case when month(order_date)<=4 then 'q1' when month(order_date)<=8 then 'q2' when month(order_date)<=12 then 'q3' end)quarter
from bab_orders
group by quarter;

However this query does not show the value of a particular quarter when it has no orders associated with it. How do I display that?

Best Answer

To display the given format, you can use the following queries instead:

For MySQL, use the following:

  SELECT QuaterName, COUNT(OrderID) FROM
    (
        SELECT QUARTER(OrderDate) QuaterName, OrderID from bab_orders
    ) T1 group by QuaterName; 

for Oracle use the following:

SELECT QuaterName, COUNT(OrderID) FROM
(
    SELECT TO_CHAR(TO_DATE(OrderDate, 'dd.mm.yyyy'), 'Q') 
              QuaterName, OrderID from bab_orders
) T1 group by QuaterName; 

to show always the Quarters even if you don't have a data, execute the following query:

SELECT QRTR, COUNT(OrderID) TheCount FROM
(
  SELECT QUARTER('2014-01-01')  QRTR  
  union
  SELECT QUARTER('2014-04-01')  QRTR
  union
  SELECT QUARTER('2014-08-01')  QRTR
  union
  SELECT QUARTER('2014-12-01')  QRTR
)  QRTR_T
LEFT JOIN 
(
   SELECT QUARTER(OrderDate) Quater, OrderID from bab_orders
) ORDERS
on Quater = QRTR
group by QRTR