根据以下设置,对于每个CD_name
,我如何找出购买次数最多的天数。我的结果表应列出CD_no
和当天的日期(别名为“最繁忙”)。如果在购买数量相等的几天内,CD可以在结果表中显示几个时间,因此按字母顺序将结果表按CD_no
排序,对于相同的CD_no,按日期排序最早的。
CREATE TABLE CD
(
CD_no TINYINT UNSIGNED,
genre VARCHAR(60),
purchase_date DATE NOT NULL,
publication_time TIME NOT NULL,
Artist VARCHAR(20)
);
预期输出列出了CD_number以及最繁忙的一天的日期,也可以在具有相同购买量的几天内出现CD编号。
例如,包含以下数据:
CD_No purchase_date
1 2012-07-09
1 2012-07-09
1 2012-07-09
1 2012-07-10
1 2012-07-10
2 2012-11-11
2 2012-11-11
2 2012-11-12
2 2012-11-12
应该有以下结果表:
CD_NO Busiest
1 2012-07-09
2 2012-11-11
2 2012-11-12
因为cd_no 1在该日期的销售额最多,而且cd_no 2有联合购买。
答案 0 :(得分:2)
select CD_no,
purchase_date as busiest
from CD
group by CD_no, purchase_date
order by count(purchase_date) desc,
CD_no asc,
purchase_date asc
limit 3
答案 1 :(得分:1)
create view purchases as
select cd_no, purchase_date, count(*) as purchases
from cd
group by cd_no, purchase_date;
select p1.cd_no, p1.purchase_date as busiest
from purchases p1
join (select cd_no, max(purchases) as purchases
from purchases
group by cd_no) as p2
on p1.cd_no = p2.cd_no and p1.purchases = p2.purchases
order by p1.cd_no, p1.purchase_date;