SQL查询中的复杂计算

时间:2011-03-03 21:06:35

标签: mysql sql oracle oracle-xe ora-00932

昨天我用相同的代码发布了一个类似的问题,我已经重写了,它应该是新规范的完美,但由于某种原因它不起作用。

我正在使用Oracle 10g Express。

以下代码正在计算收入最高的10%的律师。

CREATE VIEW rich_solicitors AS
select notes.time_spent*rate.rate_amnt+coalesce(special_rate.s_rate_amnt,0)
AS solicitor_made, notes.solicitor_id
FROM notes, rate, solicitor_rate, solicitor, case, contract, special_rate
WHERE notes.solicitor_id = solicitor.solicitor_id
AND solicitor.solicitor_id = solicitor_rate.solicitor_id
AND solicitor_rate.rate_id = rate.rate_id
AND notes.case_id = case.case_id
AND case.contract_id = contract.contract_id
AND contract.contract_id = special_rate.contract_id (+)
ORDER BY -solicitor_made;


SELECT * FROM rich_solicitors
WHERE ROWNUM <= (SELECT COUNT(*)/10 FROM rich_solicitors);

我需要计算去年的前10%,我认为这就像将start_date和expiry_date添加到SELECT并添加以下WHERE函数一样简单:

AND contract.start_date >= 01-01-10
AND contract.expiry_date <= 01-01-11

我已使用TO_DATE核心插入日期。我的讲师花了一个小时与我一起研究为什么这种方法无效但无济于事。

它一直在返回错误 - ORA-00932:不一致的数据类型:预期的CHAR有NUMBER

我也尝试定义日期格式,但仍然返回相同的错误

CREATE VIEW rich_solicitors1 AS
SELECT  notes.time_spent*rate.rate_amnt+coalesce(special_rate.s_rate_amnt,0) AS solicitor_made, notes.solicitor_id, TO_CHAR(contract.start_date, 'DD-MM-YY'), TO_CHAR(contract.expiry_date, 'DD-MM-YY')
FROM notes, rate, solicitor_rate, solicitor, case, contract, special_rate
WHERE notes.solicitor_id = solicitor.solicitor_id
AND solicitor.solicitor_id = solicitor_rate.solicitor_id
AND solicitor_rate.rate_id = rate.rate_id
AND notes.case_id = case.case_id
AND case.contract_id = contract.contract_id
AND contract.contract_id = special_rate.contract_id (+)
AND contract.start_date >= 01-01-10
AND contract.expiry_date <= 01-01-11
ORDER BY -solicitor_made;

任何想法?

非常感谢,任何批评都非常感谢,我是一名学生,并且在我第一步这样做之前,大约9天前我根本没有SQL知识。

2 个答案:

答案 0 :(得分:3)

你能尝试用NVL功能替换你的合并

吗?
SELECT  notes.time_spent*rate.rate_amnt+NVL(special_rate.s_rate_amnt,0) 
AS solicitor_made, notes.solicitor_id, TO_CHAR(contract.start_date, 'DD-MM-YY'), 
TO_CHAR(contract.expiry_date, 'DD-MM-YY') 
FROM notes, rate, solicitor_rate, solicitor, case, contract, special_rate 
WHERE notes.solicitor_id = solicitor.solicitor_id 
AND solicitor.solicitor_id = solicitor_rate.solicitor_id 
AND solicitor_rate.rate_id = rate.rate_id AND notes.case_id = case.case_id 
AND case.contract_id = contract.contract_id 
AND contract.contract_id = special_rate.contract_id (+) 
AND contract.start_date >= to_date('01-01-10','MM-DD-YY')
AND contract.expiry_date <= to_date('01-01-11' ,'MM-DD-YY')
ORDER BY solicitor_made

答案 1 :(得分:2)

Phil,使用ROWNUM的查询将通过我能想到的任何“top”定义获得前10%。

一个例子是:

SELECT * FROM (
  SELECT solicitor_made, solicitor_id
        ,NTILE(10) OVER (ORDER BY solicitor_made DESC) decile
  FROM rich_solicitors
) WHERE decile = 1;

修改

注意到你的视图定义中有ORDER BY。在这种情况下,您的ROWNUM方法将起作用。通常我建议不要在视图定义中放置ORDER BY。