我试图在给定的月份(JAN-14)中显示最受欢迎的产品(format_id),并将它们按每个format_id的计数进行分组。
这是我的查询:
select PRODUCT, AMOUNT
from (Select Order_108681091.Order_Date, order_line_108681091.Format_id as Product,
COUNT(*) AS AMOUNT FROM order_line_108681091
Inner Join order_108681091
On order_108681091.order_id = order_line_108681091.order_id
Where order_108681091.Order_Date like '%JAN-14%'
group by Format_id
order by AMOUNT desc);
我该怎么做?
答案 0 :(得分:1)
您必须指定内部联接:
inner join order_108681091 ON order_1078681091.ID = order_line_018681091.ID
或类似的东西。除非您将该日期存储为字符串而不是datetime数据类型,否则您的where子句可能无法工作。
答案 1 :(得分:1)
ORDER BY
,因此请将其删除。Order_date
SELECT
SELECT l.Format_id as PRODUCT, COUNT(*) AS AMOUNT FROM order_line_108681091 l INNER JOIN order_108681091 o ON o.order_id = l.order_id WHERE o.Order_Date LIKE '%JAN-14%' GROUP BY l.Format_id;
答案 2 :(得分:1)
根本不需要子查询。而且,我直接在日期使用like
时感到非常不舒服。将日期显式转换为字符串:
select ol.Format_id as Product, COUNT(*) AS AMOUNT
from order_line_108681091 ol Inner Join
order_108681091 o
ON o.order_id = ol.order_id
where to_char(o.Order_Date, 'MMM-YYYY') = 'JAN-2014'
group by ol.Format_id
order by count(*) desc;
实际上,如果您在OrderDate
上有索引,则可以使用以下内容(以利用索引):
select ol.Format_id as Product, COUNT(*) AS AMOUNT
from order_line_108681091 ol Inner Join
order_108681091 o
ON o.order_id = ol.order_id
where o.Order_Date >= to_date('2014-01-01', 'YYYY-MM-DD') and
o.Order_Date < to_date('2014-02-01', 'YYYY-MM-DD')
group by ol.Format_id
order by count(*) desc;
将函数从列移动到常量允许在列上使用索引。