这是我的代码:
SELECT account_name,
count(ordered_item),
ROW_NUMBER() OVER (
PARTITION BY account_name, ordered_item
ORDER BY count(ordered_item) DESC
) Row
FROM oe_order_lines_all ool,
cust_accounts_all hca,
oe_order_headers_all ooh
WHERE to_date(ooh.creation_date) BETWEEN '2015-10-01' AND '2015-10-31'
AND ooh.flow_status_code <> 'CANCELLED'
AND ooh.sys_document_ref = ool.sys_document_ref
AND hca.cust_account_id = ooh.org_id
GROUP BY hca.account_name,
ool.ordered_item
ORDER BY ool.ordered_item DESC
我一直收到错误&#34; FROM关键字未找到预期位置&#34;。我不确定我的语法有什么问题。我试图查看哪个帐户(有多个具有相同名称,即亚马逊)的订单项最多。还有其他方法可以找到这些信息吗?我的代码中有什么错误?
提前感谢您的帮助!
答案 0 :(得分:1)
当前问题是ROW
是a reserved word。如果您将该列别名更改为其他错误将会消失的内容。
但是您可能希望子查询获取每个帐户名的计数,然后将分析函数应用于该结果 - 没有PARTITION BY
子句将对所有内容进行排名:
SELECT account_name, ordered_items,
ROW_NUMBER() OVER (
ORDER BY ordered_items DESC
) rn
FROM (
SELECT hca.account_name,
count(ordered_item) ordered_items
FROM oe_order_headers_all ooh
JOIN oe_order_lines_all ool
ON ooh.sys_document_ref = ool.sys_document_ref
JOIN cust_accounts_all hca
ON hca.cust_account_id = ooh.org_id
WHERE to_date(ooh.creation_date) BETWEEN DATE '2015-10-01' AND DATE '2015-10-31'
AND ooh.flow_status_code <> 'CANCELLED'
GROUP BY hca.account_name
)
ORDER BY rn DESC;
如果你只想要一个计数最高的那个你可以有更高的水平:
SELECT account_name, ordered_items
FROM (
SELECT account_name, ordered_items,
ROW_NUMBER() OVER (
ORDER BY ordered_items DESC
) rn
FROM (
SELECT hca.account_name,
count(ordered_item) ordered_items
FROM oe_order_headers_all ooh
JOIN oe_order_lines_all ool
ON ooh.sys_document_ref = ool.sys_document_ref
JOIN cust_accounts_all hca
ON hca.cust_account_id = ooh.org_id
WHERE to_date(ooh.creation_date) BETWEEN DATE '2015-10-01' AND DATE '2015-10-31'
AND ooh.flow_status_code <> 'CANCELLED'
GROUP BY hca.account_name
)
)
WHERE rn = 1;
但ROW_NUMBER()
可能不合适。您没有指定如果两个帐户具有相同的计数会发生什么。如果你只想显示其中一个,你需要一种方法来选择使用哪个,你可以通过在函数的ORDER BY
子句中添加一个tie-braker来做。如果您想要同时显示两者,请改为使用RANK()
。
(我也切换到ANSI连接;并使用日期文字,因此您不依赖于NLS设置。)
答案 1 :(得分:1)
我认为您需要执行子查询
SELECT account_name,
ordered_item,
ROW_NUMBER() OVER (ORDER BY Total DESC) as rn
FROM (
SELECT hca.account_name,
ool.ordered_item,
COUNT(*) as total
FROM oe_order_lines_all ool
JOIN oe_order_headers_all ooh
ON ooh.sys_document_ref = ool.sys_document_ref
JOIN cust_accounts_all hca
ON hca.cust_account_id = ooh.org_id
WHERE to_date(ooh.creation_date) BETWEEN '2015-10-01' AND '2015-10-31'
AND ooh.flow_status_code <> 'CANCELLED'
GROUP BY
hca.account_name,
ool.ordered_item
) T
ORDER BY ordered_item DESC