SELECT DISTINCT(id_no), lastname,
(SELECT COUNT(purchasedate) num_of_purch
FROM sales JOIN Artist ON
sales.id = Artist.id_no
WHERE DATE_SUB(CURDATE(),INTERVAL 1
YEAR) <= purchasedate
) AS num_of_purch
FROM Artist
此查询返回所有艺术家的ID_no,他们的姓氏和购买总数,我想指定哪些购买是哪个艺术家。有助于解决这个问题。
编辑 - DISTINCT(id_no)是多余的,因为它是主键。
答案 0 :(得分:2)
显示每个artist_id的销售数量:
SELECT artist.id_no, count(sales.id) as num_of_purch
FROM artist left join sales on sales.id = artist.id_no
WHERE DATE_SUB(CURDATE(), INTERVAL 1 YEAR) <= purchasedate
GROUP BY artist.id
还要返回姓氏和所有细节:
SELECT art_tot.id_no, art_tot.lastname, art_tot.num_of_purch, sales.*
FROM (SELECT artist.id_no, artist.lastname, count(sales.id) as num_of_purch
FROM artist left join sales on sales.id = artist.id_no
WHERE DATE_SUB(CURDATE(), INTERVAL 1 YEAR) <= purchasedate
GOUP BY artist.id, artist.lastname) art_tot
left join sales on art_tot.id_no = sales.id
答案 1 :(得分:1)
这应该为您提供艺术家和每位艺术家的购买数量
select a.id_no, a.lastname, count(s.purchasedate) num_of_purch
from artists a
join sales s on a.id_no = s.id
where date_sub(curdate(), interval 1 year) <= s.purchasedate
group by a.id_no, a.lastname
答案 2 :(得分:0)
您应该使用GROUP BY来获取每个艺术家的计数。
你应该使用外部联接来包括去年没有销售的艺术家。
SELECT a.id_no, a.lastname, COUNT(s.purchasedate) AS num_of_purch
FROM Artist a
LEFT OUTER JOIN sales s ON s.id = a.id_no
AND s.purchasedate => CURDATE() - INTERVAL 1 YEAR
GROUP BY a.id_no;
PS:使用DISTINCT(id_no)
没有意义,不仅因为id_no已经是唯一键,而且因为DISTINCT始终适用于选择列表中的所有列,即使您添加了括号来制作它看起来像一个仅适用于一列的函数。