Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql Select from Select

I have this query:

    SELECT DATE( a.created_at ) AS order_date, count( * ) as cnt_order
    FROM `sales_order_item` AS a
    WHERE MONTH( a.created_at ) = MONTH( now())-1
    GROUP BY order_date

which will return result something like this (snapshot only otherwise will return per 31 days):

order_date  cnt_order 
2012-08-29  580
2012-08-30  839
2012-08-31  1075

and my full query is selecting based on above selection:

SELECT order_date
    , MAX(cnt_order) AS highest_order
FROM (
        SELECT DATE (a.created_at) AS order_date
            , count(*) AS cnt_order
        FROM `sales_order_item` AS a
        WHERE MONTH(a.created_at) = MONTH(now()) - 1
        GROUP BY order_date
    ) AS tmax

But it result :

order_date  highest_order
2012-08-01  1075

Which has the date wrong and always pick the first row of date where it suppose 2012-08-31. Maybe this is a simple error that I dont know. So how to get the date right point to 2012-08-31? Any help would be great.

like image 856
Ardeus Avatar asked Sep 20 '12 05:09

Ardeus


People also ask

Can we use SELECT inside SELECT in MySQL?

In MySQL subquery can be nested inside a SELECT, INSERT, UPDATE, DELETE, SET, or DO statement or inside another subquery. A subquery is usually added within the WHERE Clause of another SQL SELECT statement.

Can you put a SELECT statement in a SELECT statement?

You can construct a SELECT statement with a subquery to replace two separate SELECT statements. Subqueries in SELECT statements allow you to perform the following actions: Compare an expression to the result of another SELECT statement. Determine whether the results of another SELECT statement include an expression.

What is SELECT * from in MySQL?

The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.

What is a sub query in MySQL?

A subquery is a SELECT statement within another statement. All subquery forms and operations that the SQL standard requires are supported, as well as a few features that are MySQL-specific.


1 Answers

You could try ordering the sub query result set; something like:

SELECT
    DATE (a.created_at) AS order_date,
    COUNT(*) AS cnt_order
FROM
    `sales_order_item` AS a
WHERE
    MONTH(a.created_at) = MONTH(now()) - 1
GROUP BY
    order_date
ORDER BY
    cnt_order DESC
like image 180
Zaki Avatar answered Oct 06 '22 01:10

Zaki