Place the results of a MySQL query into a CSV file

The results of a MySQL query can be placed into a CSV file using the following query:

INTO OUTFILE 'file_path'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

To include header write another query before the “main” query. It returns the header, and the “main” query returns the data. Union joins them together:

SELECT 'COLUMN1_NAME', 'COLUMN2_NAME'
UNION 
… Your MySQL query here;

View on Github

Magento MySQL – Calculate average number of orders per day and per month

What is the average number of orders per day?

SELECT AVG( orders_num )
FROM (
SELECT created_at, COUNT( DISTINCT order_id ) orders_num
FROM `sales_flat_order_item`
GROUP BY CAST( created_at AS DATE )
)orders_per_day

What is the average number of orders per month?

SELECT AVG( orders_num ) 
FROM (
SELECT created_at, COUNT( DISTINCT order_id ) orders_num
FROM  `sales_flat_order_item` 
GROUP BY MONTH( created_at )
)orders_per_month

View on Github