我试图同时显示MIN& MAX加入几张表格以获取信息。我得到了MIN& MAX但它显示我其他字段的错误信息。
SELECT
SONG.SONG_NAME,
ALBUM.ALBUM_NAME,
ARTIST.ARTIST_NAME,
MAX(SONG.LENGTH_SECONDS) AS LENGTH
FROM SONG
JOIN ALBUM ON ALBUM.ALBUM_ID = SONG.ALBUM_ID
JOIN ARTIST ON ARTIST.ARTIST_ID = SONG.ARTIST_ID
UNION
SELECT
SONG.SONG_NAME,
ALBUM.ALBUM_NAME,
ARTIST.ARTIST_NAME,
MIN(SONG.LENGTH_SECONDS)
FROM SONG
JOIN ALBUM ON ALBUM.ALBUM_ID = SONG.ALBUM_ID
JOIN ARTIST ON ARTIST.ARTIST_ID = SONG.ARTIST_ID;
这些是我在查询中得到的结果:
| SONG_NAME | ALBUM_NAME | ARTIST_NAME | LENGTH |
+------------------------+---------------------------+----------------+--------+
| Fluorescent Adolescent | Favourite Worst Nightmare | Arctic Monkeys | 390 |
| Fluorescent Adolescent | Favourite Worst Nightmare | Arctic Monkeys | 177 |
答案 0 :(得分:0)
您可以删除MAX&从SELECT中选择MIN并添加TOP 1。然后添加ORDER BY SONG.LENGTH_SECONDS以获得最短的歌曲和ORDER BY SONG.LENGTH_SECONDS DESC以获得最长的歌曲。
SELECT TOP 1
SONG.SONG_NAME,
ALBUM.ALBUM_NAME,
ARTIST.ARTIST_NAME,
SONG.LENGTH_SECONDS AS LENGTH
FROM SONG
JOIN ALBUM ON ALBUM.ALBUM_ID = SONG.ALBUM_ID
JOIN ARTIST ON ARTIST.ARTIST_ID = SONG.ARTIST_ID
ORDER BY SONG.LENGTH_SECONDS DESC
UNION
SELECT TOP 1
SONG.SONG_NAME,
ALBUM.ALBUM_NAME,
ARTIST.ARTIST_NAME,
SONG.LENGTH_SECONDS AS LENGTH
FROM SONG
JOIN ALBUM ON ALBUM.ALBUM_ID = SONG.ALBUM_ID
JOIN ARTIST ON ARTIST.ARTIST_ID = SONG.ARTIST_ID;
ORDER BY SONG.LENGTH_SECONDS
答案 1 :(得分:0)
假设您正在为每位艺术家和专辑寻找歌曲的最小和最长持续时间,并为这些歌曲获取歌曲名称
您可以使用按SONG.ALBUM_ID,ALBUM.ALBUM_NAME,ARTIST.ARTIST_NAME分组的联合 加入歌曲以获得正确的歌曲名称
select song.song_name, t.ALBUM_NAME, t.ARTIST_NAME, t.LENGTH
from song
inner join (
SELECT
SONG.ALBUM_ID
ALBUM.ALBUM_NAME,
ARTIST.ARTIST_NAME,
MAX(SONG.LENGTH_SECONDS) AS LENGTH
FROM SONG
JOIN ALBUM ON ALBUM.ALBUM_ID = SONG.ALBUM_ID
JOIN ARTIST ON ARTIST.ARTIST_ID = SONG.ARTIST_ID
GROUP BY SONG.ALBUM_ID,ALBUM.ALBUM_NAME, ARTIST.ARTIST_NAME
) T on song.album_id = t.album_id and t.LENGTH = song.LENGTH_SECONDS
UNION
select song.song_name, t.ALBUM_NAME, t.ARTIST_NAME, t.LENGTH
from song
inner join (
SELECT
SONG.ALBUM_ID
ALBUM.ALBUM_NAME,
ARTIST.ARTIST_NAME,
MIN(SONG.LENGTH_SECONDS) AS LENGTH
FROM SONG
JOIN ALBUM ON ALBUM.ALBUM_ID = SONG.ALBUM_ID
JOIN ARTIST ON ARTIST.ARTIST_ID = SONG.ARTIST_ID
GROUP BY SONG.ALBUM_ID,ALBUM.ALBUM_NAME, ARTIST.ARTIST_NAME
) T on song.album_id = t.album_id and t.LENGTH = song.LENGTH_SECONDS