mysql按groupby后的列顺序排序

时间:2013-09-19 04:50:52

标签: mysql group-by sql-order-by

我有一个包含以下字段的表:season,collection,product_key,aggregated_sale。以下查询未给出预期输出

select
    t.* 
from
    (SELECT * FROM rank_processing.aggregate_season_product 
       order by aggregated_sale) t
group by
    t.collection,
    t.forecast_name,
    t.product_key;

示例输入

ss, f1, 1, 11
ss, f1, 3, 10
ss, f1, 2, 5
ss, f2, 5, 11
ss, f2, 4, 7

预期产出

ss, f1, 2, 5
ss, f1, 3, 10
ss, f1, 1, 11
ss, f2, 4, 7
ss, f2, 5, 11

3 个答案:

答案 0 :(得分:1)

请注意,如果没有明确的ORDER BY子句服务器,则不需要对结果进行排序,即使存在GROUP BY也是如此。

如果您想订购结果,只需添加适当的ORDER BY,类似:

SELECT t.* 
FROM (SELECT * FROM rank_processing.aggregate_season_product 
    ORDER BY aggregated_sale) t
GROUP BY
    t.collection,
    t.forecast_name,
    t.product_key
ORDER BY
    t.collection,
    t.forecast_name,
    t.product_key

这里的另一个问题是子查询中的ORDER BY是无用的,你甚至应该扩展该子查询以完全消除它。

答案 1 :(得分:1)

为什么需要使用子查询?此查询应该为您提供结果。

SELECT * FROM rank_processing.aggregate_season_product 
group by
  collection,
  forecast_name,
  product_key
order by season, collection, aggregated_sale

我猜,你甚至不需要GROUP BY

SELECT * FROM rank_processing.aggregate_season_product 
order by season, collection, aggregated_sale

答案 2 :(得分:0)

SQL Fiddle

MySQL 5.5.32架构设置

CREATE TABLE aggregate_season_product
    (`season` varchar(2), `collection` varchar(2), `forecast_name` varchar(2), `product_key` int, `aggregated_sale` int)
;

INSERT INTO aggregate_season_product
    (`season`, `collection`, `forecast_name`, `product_key`, `aggregated_sale`)
VALUES
    ('ss', 'cc', 'f1', 1, 11),
    ('ss', 'cc', 'f1', 3, 10),
    ('ss', 'cc', 'f1', 2, 5),
    ('ss', 'cc', 'f2', 5, 11),
    ('ss', 'cc', 'f2', 4, 7)
;

查询1

select * 
from aggregate_season_product 
where season = 'ss' and collection = 'cc'
ORDER by
    season,
    collection,
    forecast_name,
    aggregated_sale

<强> Results

| SEASON | COLLECTION | FORECAST_NAME | PRODUCT_KEY | AGGREGATED_SALE |
|--------|------------|---------------|-------------|-----------------|
|     ss |         cc |            f1 |           2 |               5 |
|     ss |         cc |            f1 |           3 |              10 |
|     ss |         cc |            f1 |           1 |              11 |
|     ss |         cc |            f2 |           4 |               7 |
|     ss |         cc |            f2 |           5 |              11 |