[英]SQL DISTINCT plus count
I currently have a table with album name, artist, and title in it (for Mp3s). 我目前有一张桌子,上面有专辑的名称,艺术家和标题(适用于Mp3)。 On my webpage on the left I currently display all album names using:
目前,我在左侧的网页上使用以下命令显示所有相册名称:
SELEC DISTINCT `album` FROM `mp3`
But I would like to display the amount of each album next to it, for instance: 但我想显示每张专辑旁边的数量,例如:
A Very Good Album (3)
Indicating that there are 3 entires in that record. 表示该记录中有3个整体。 Can I do this with SQL?
我可以使用SQL吗? Select Distinct, but also find out how many are with that album?
选择Distinct,还要找出这张专辑有多少张?
Rather than DISTINCT
, this is really a basic COUNT()
aggregate grouped by album
. 与其说是
DISTINCT
, DISTINCT
说是按album
分组的基本COUNT()
聚合 。
SELECT
album,
COUNT(*) AS num_records
FROM
mp3
GROUP BY album
If you want it in the parentheses inside the SQL query , use CONCAT()
. 如果要在SQL查询内的括号中使用它,请使用
CONCAT()
。 This is probably best left to your application for display though. 不过,最好将其留给您的应用程序进行显示。
SELECT
/* The album title, and count in () as one column as a single string */
/* like "A Very Good Album (3)" */
CONCAT(album, ' (', COUNT(*), ')') AS album
FROM
mp3
GROUP BY album
尝试这个:
SELECT `album`, COUNT(*) FROM `mp3` GROUP BY `album`
You want a group by
: 您想要一个
group by
:
select album, count(*)
from mp3
group by album
use the group by and concat the string like this 使用group by并像这样连接字符串
SELECT
CONCAT(`album`, ' (', COUNT(*), ')') as album
FROM `mp3`
GROUP BY `album`
SELECT DISTINCT CONCAT(album, ' (', COUNT(DISTINCT album), ')') AS album
FROM mp3
GROUP BY album
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.