我需要有关SQL测试中问题的帮助。
假设我有两个表,即Album(album_id)和DailySells(album_id,date,albums_sold),并加入了他们
select id
from album join daily using(id)
where (date, albsold) in (select date, min(albsold)
from daily
group by date
having min(albsold) = (select max(worstdaily)
from (select date, min(albsold) as worstdaily
from daily
group by date) as inner))
问题是:每天显示最畅销专辑中最畅销的专辑。
因此,我需要每天获取销量最差的专辑,然后提取其中销量最好的一张。我看到答案应该显示为1111(日期22,albums_sold 3)。
您能帮我编写一个可以解决此问题的查询吗?
谢谢!
编辑:很抱歉,我为此花了3个多小时的时间,但没有显示代码。这是我一直在尝试的方法:
var colors = ["teal", "violet", "silver", "green", "red", "purple"];
var count;
for (count = 0; count < colors.length; count++) {
console.log(colors[count]);
stringLength(colors[count]);
}
function stringLength(string) {
if (string.length > 4) {
console.log("greater than 4");
} else if (string.length < 4) {
console.log("less than 4");
} else {
console.log("is equal to 4");
}
}
答案 0 :(得分:0)
在子查询中,我们仅按日期记录MIN(albums_sold)值的记录,然后按albums_sold DESC排序,并使用TOP(1)取MAX:
SELECT TOP(1) mt.*
FROM alb mt INNER JOIN
(
SELECT date, MIN(albums_sold) MinSold
FROM alb
GROUP BY date
) t ON mt.date = t.date AND mt.albums_sold = t.MinSold
ORDER BY albums_sold DESC
答案 1 :(得分:0)
有几种方法可以解决此问题。无论如何,我们必须牢记可能存在联系(一天中有多个最差的卖家,或者最差的多个卖家),并决定如何处理。我正在考虑所有相关的行,因此结果可能会跨越多行。
这是一些标准的SQL查询。您的DBMS可能支持也可能不支持。
查询1
select album_id
from mytable
where not exists
(
select *
from mytable other
where other.date = mytable.date
and other.albums_sold < mytable.albums_sold
)
order by albums_sold desc
fetch first 1 row with ties;
查询2
select album_id
from
(
select album_id, albums_sold, rank() over (partition by date order by albums_sold) as rn
from mytable other
) ranked
where rn = 1
order by albums_sold desc
fetch first 1 row with ties;
查询3
select album_id
from
(
select album_id, albums_sold
from mytable other
order by rank() over (partition by date order by albums_sold)
fetch first 1 row with ties
) worst
order by albums_sold desc
fetch first 1 row with ties;
您会看到可以组合使用以下方法:子查询,排名,先获取。