简体   繁体   中英

SQL ORDER BY command not working with GROUP BY

I am creating a new table that sums the values from the stock table for each item_id and then puts them into the new table. This works fine using this code:

create table total_stock as (
select item_id,
sum (stock) total_stock
from stock_tbl
group by item_id
);

which works fine, adding all the values from the stock table and putting them into the new table, but when I try to order it by item_id it doesn't work. Any help would be appreciated. The error given is a syntax error.

create table total_stock as (
select item_id,
sum (stock) total_stock
from stock_tbl
group by item_id
order by item_id
);

Rows in a database table are stored without any particular order. That is why specifying order by when filling a table doesn't work.

You have to order by when selecting rows from a table, not when entering rows into a table.

Technically, you can order the rows in a table in most databases. You do this by creating a clustered index on the keys used for the ordering.

Guess what?

select t.*
from t

still doesn't return the rows in order, even in tables that have a clustered index. *At least, there is no guarantee. *SQL result sets are unordered unless an ORDER BY is explicitly included for the outermost SELECT . The only guarantee on the ordering of a result set is to use order by . In your case, that would be:

select item_id, sum(stock) as total_stock
from stock_tbl
group by item_id
order by item_id;

or:

select ts.*
from total_stock ts
order by item_id;

By the way, using a temporary table for this is not recommended unless you have a specific need to materialize the result set.

Updated You can use Common Table Expression and then use this data to insert into your table, as

with CTE as (
select item_id, sum(stock) total stock
from stock_table
) Insert into total_stock
select * from cte group by item_id order by item_id

This should solve your problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM