用于获取SQL Server中所有类别相册的专辑计数的SQL查询

时间:2016-12-06 04:16:07

标签: sql-server sql-server-2008

我希望AlbumCategories显示每个类别的Albums计数,如下所示。

期望的结果:

Sports(2)
Education(3)
Community(0)
Something(0)

查询:

SELECT 
    AC.ACID, MAX(AC.Name) as Name,
    COUNT(*) as Frequency 
FROM 
    Album A
INNER JOIN 
    AlbumCategories AC ON A.ACID = AC.ACID
GROUP BY 
    AC.ACID  

此查询仅返回AlbumCategories,其中包含以上查询

的相册示例输出
Sports(2)
Education(3)

相册类别

ACID    Name
1       Sports
2       Education
3       Community
4       Something

相册

AID     ACID    Name
1       1       Footbal season 2015
2       1       Footbal season 2016
3       2       Album one
4       2       Album Two
5       2       Album Three

相册图片

PID     AID Image

1 个答案:

答案 0 :(得分:3)

您需要使用RIGHT JOININNER JOIN仅提取连接表之间的匹配记录。从Album表计算列不要使用*

架构设置

CREATE TABLE AlbumCategories
    ([ACID] int, [Name] varchar(9))
;

INSERT INTO AlbumCategories
    ([ACID], [Name])
VALUES
    (1, 'Sports'),
    (2, 'Education'),
    (3, 'Community'),
    (4, 'Something');


CREATE TABLE albums
    ([AID] int, [ACID] int, [Name] varchar(19))
;

INSERT INTO albums
    ([AID], [ACID], [Name])
VALUES
    (1, 1, 'Footbal season 2015'),
    (2, 1, 'Footbal season 2016'),
    (3, 2, 'Album one'),
    (4, 2, 'Album Two'),
    (5, 2, 'Album Three');

查询

SELECT AC.ACID,
       AC.NAME       AS NAME,
       Count(A.ACID) AS Frequency
FROM   albums A
       RIGHT JOIN AlbumCategories AC
               ON A.ACID = AC.ACID
GROUP  BY AC.ACID,
          AC.NAME 

结果:

╔══════╦═══════════╦═══════════╗
║ ACID ║   NAME    ║ Frequency ║
╠══════╬═══════════╬═══════════╣
║    1 ║ Sports    ║         2 ║
║    2 ║ Education ║         3 ║
║    3 ║ Community ║         0 ║
║    4 ║ Something ║         0 ║
╚══════╩═══════════╩═══════════╝