如何打印从分组获得的查询结果的每个值

时间:2019-02-16 15:34:07

标签: mysql sql group-by concatenation

SELECT DISTINCT OCCUPATION, COUNT(*)
FROM OCCUPATIONS
GROUP BY OCCUPATION
ORDER BY COUNT(*), OCCUPATION ASC;

以上查询将为我提供独特的职业及其出现次数的升序排列。现在我要使用结果来打印语句

There are a total of [occupation_count] [occupation]s.

我尝试过

SELECT  CONCAT('There are a total of ', COUNT(*), DISTINCT OCCUPATION, 's.')
FROM OCCUPATIONS
GROUP BY OCCUPATION
ORDER BY COUNT(*), OCCUPATION ASC;

但是出现语法错误。 每个不同的职业。

我该怎么做?我应该写一个子查询吗?

1 个答案:

答案 0 :(得分:1)

在使用DISTINCT的查询中几乎不需要

GROUP BY,因此您的查询不需要它。因此,只需使用:

SELECT CONCAT('There are a total of ', COUNT(*), ' ', OCCUPATION, 's.')
FROM OCCUPATIONS
GROUP BY OCCUPATION
ORDER BY COUNT(*), OCCUPATION ASC;

请注意,SELECT DISTINCT是一个关键字,例如LEFT JOINIS NULL。关键字之间应该没有任何关系。