-1

我有一个包含以下字段的表:季节、集合、product_key、aggreged_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
4

3 回答 3

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内部子查询是无用的,您甚至应该扩展该子查询以完全消除它。

于 2013-09-19T05:05:28.133 回答
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
于 2013-09-19T05:06:04.593 回答
0

SQL小提琴

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

结果

| 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 |
于 2013-09-19T05:10:34.690 回答