简体   繁体   中英

SQL DISTINCT plus count

I currently have a table with album name, artist, and title in it (for Mp3s). 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. Can I do this with SQL? Select Distinct, but also find out how many are with that album?

Rather than DISTINCT , this is really a basic COUNT() aggregate grouped by album .

SELECT
  album,
  COUNT(*) AS num_records
FROM 
  mp3
GROUP BY album

If you want it in the parentheses inside the SQL query , use 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 :

select album, count(*)
from mp3
group by album

use the group by and concat the string like this

SELECT
    CONCAT(`album`, ' (', COUNT(*), ')') as album
FROM `mp3`
GROUP BY `album`

看看Count()Group By

SELECT DISTINCT CONCAT(album, ' (', COUNT(DISTINCT album), ')') AS album
FROM            mp3
GROUP BY        album

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM