假设我有这张汽车销售表:
DESCRIPTION AMOUNT -------------- ------- Ford: Tarus $10,000 Honda: Accord $11,000 Honda: Accord $12,000 Chevy: Equinox $13,000 Ford: Explorer $14,000 Ford: Explorer $15,000 Dodge: Dart $16,000 Ford: Explorer $17,000
If I want to see the total money brought in by each unique description I could say:
SELECT description, count(description) AS sales_count, SUM(amount) AS total_amount
FROM car_sales
GROUP BY description
ORDER BY total_amount DESC, sales_count DESC
并得到这样一份不错的报告:
DESCRIPTION SALES_COUNT TOTAL_AMOUNT -------------- ----------- ------------ Ford: Explorer 3 $46,000 Honda: Accord 2 $23,000 Dodge: Dart 1 $16,000 Chevy: Equinox 1 $13,000 Ford: Tarus 1 $10,000
现在请注意,我的描述只是用冒号分隔的品牌和型号。我无法更改描述列的格式设置方式,但我希望得到一个响应,显示按品牌和型号分割的信息。有点像在 : 冒号
上拆分它。我将如何编写我的 SQL 查询来执行此操作并获得这样的表?
DESCRIPTION SALES_COUNT TOTAL_AMOUNT -------------- ----------- ------------ Ford 4 $56,000 Explorer 3 $46,000 Tarus 1 $10,000 Honda 2 $23,000 Accord 2 $23,000 Dodge 1 $16,000 Dart 1 $16,000 Chevy 1 $13,000 Equinox 1 $13,000
最佳答案
您可以使用 group by
上的 with rollup
选项(MySQL 和 SQL Server 都支持)来做您想做的事。在 MySQL 中,您可以这样做:
SELECT substring_index(description, ':', 1) as make,
substring_index(description, ':', 2) as model,
count(description) AS sales_count, SUM(amount) AS total_amount
FROM car_sales cs
GROUP BY substring_index(description, ':', 1),
substring_index(description, ':', 2) with rollup;
这不是完全您请求的输出。这会将品牌和型号放在不同的列中,并包括总计。
你不能将 order by
与 rollup
一起使用,唉。如果您使用子查询,则可以这样做。但是,这可能无法满足您的要求,因为它会对所有 行进行排序,包括具有汇总值的行。
关于MySQL 使用 Group By 从描述字段中获取唯一值并在分隔符上拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21667748/