我正在尝试返回在指定日期范围内销售的项目类型的降序列表。
我理解如何获取Item类型的数量并计算它们,但我仍然坚持如何链接到其他表。我将把我的工作代码和psuedo放在一起,我认为它需要完成,任何帮助将不胜感激。
SELECT Item_Type, COUNT(*) as theAmount
FROM myDB.Item
//LINK order_ID to item
//WHERE order_ID includes Item_Type
//Link to session
//Find Ses_Date that order was made
GROUP BY Item_Type
ORDER BY theAmount desc
LIMIT 10
我需要三个表来提取数据,显示所需的字段:
Item
PK: Item_ID
Row: Item_Type
FK: Order_ID
Order
PK: Order_ID
FK: Session_ID
Session
PK: Ses_ID
Row: Ses_date
答案 0 :(得分:1)
SELECT i.Item_Type, COUNT(i.Item_Type) as theAmount
FROM Item AS i
JOIN Order AS o ON o.order_ID = i.Order_ID
JOIN Session AS s ON s.Ses_ID = o.Session_ID
WHERE s.Ses_date between @date1 AND @date2
GROUP BY i.Item_Type
ORDER BY theAmount DESC
LIMIT 10
答案 1 :(得分:1)
SELECT Item_Type, COUNT(*) as theAmount, Session_date
FROM Item
left outer join Order
on Item.Order_id = Order.Order_id
left outer join Session
on Order.Session_id = Session.Session_id
GROUP BY Item_Type
ORDER BY theAmount desc
LIMIT 10
以上查询将为您提供结果。
答案 2 :(得分:0)
在这种情况下你需要使用LEFT JOIN
所以如果你在另一个表上没有匹配的记录,Item_Type
的值将为零。
SELECT a.Item_Type, COUNT(c.Ses_ID) theAmount
FROM Item a
LEFT JOIN `Order` b
ON a.Order_ID = b.Order_ID
LEFT JOIN `Session` c
ON b.Session_ID = c.Ses_ID
GROUP BY a.Item_Type
-- ORDER BY theAmount DESC
-- LIMIT 10