Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL使用GROUPBY从描述字段中获取唯一值,并在分隔符上拆分_Mysql_Sql_Performance - Fatal编程技术网

MySQL使用GROUPBY从描述字段中获取唯一值,并在分隔符上拆分

MySQL使用GROUPBY从描述字段中获取唯一值,并在分隔符上拆分,mysql,sql,performance,Mysql,Sql,Performance,假设我有这张汽车销售表: 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

假设我有这张汽车销售表:

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 然后得到这样一份好的报告:

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
您可以使用
groupby
(MySQL和SQL Server都支持)上的
with rollup
选项执行您想要的操作。在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;
这不完全是您请求的输出。这将make和model放在单独的列中,并包括一个总的总数


唉,您不能将
order by
rollup
一起使用。如果使用子查询,则可以执行此操作。但是,这可能不会满足您的需要,因为它会对所有行进行排序,包括带有摘要值的行。

您使用的是MySQL还是SQL Server?我使用的是MySQL。另外,我正在用PHP编程(尽管这并不重要,因为我希望从查询中得到回复)。我想这正是我要找的Gordon!感谢您的回复,我现在就去看看。Gordon,我刚刚测试了一下,它只适用于GROUP BY,但是当我添加ORDER BY语句时,我得到一个错误,上面写着“CUBE/ROLLUP和ORDER BY的用法不正确”。我正在使用PHPMyAdmin测试查询(如果这有区别的话)。 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
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;