在连接不起作用的情况下替换Oracle SQL中的字段

时间:2014-12-05 15:58:35

标签: sql oracle

我是oracle的新手,我必须更新以下SQL以显示客户端" title"作为第一个字段,计数作为第二个字段就像现在一样。如果你看看下面的SQL是我现在拥有的,它运行得很好,但有人可以告诉我如何从客户端表中添加标题"

SQL:

select   SUBSTR(activity, INSTR(activity, '/', 1, 4) + 1, INSTR(activity, '/', 1, 5) - INSTR(activity, '/', 1, 4) -1) AS FILENAME, 
COUNT   (SUBSTR(activity, INSTR(activity, '/', 1, 4) + 1, INSTR(activity, '/', 1, 5) - INSTR(activity, '/', 1, 4)-1)) AS DOWNLOADS 
FROM access_log where id = 5555 and time_stamp BETWEEN TO_DATE ('2014/05/01', 'yyyy/mm/dd') AND TO_DATE ('2014/10/31', 'yyyy/mm/dd') 
GROUP BY SUBSTR(activity, INSTR(activity, '/', 1, 4) + 1, INSTR(activity, '/', 1, 5) - INSTR(activity, '/', 1, 4) -1) 
ORDER BY DOWNLOADS DESC;

表格

Table name: access_log
Col name: activity 
Value: Download file:/webdocs/data/groupXXX/case/03_28_54_9_0000011856.pdf
Col name: id
Value: 5555

Table name: client
Col name: id
Value: 5555
Col name: title
Value: dj cafe
如果可以,请帮助我......

它应该是这样的

**TITLE|DOWNLOADS
dj cafe|22**

2 个答案:

答案 0 :(得分:0)

由于您在其他表的列中有client值,因此您需要jointables上的两个ID。并在select列表中包含列名称ID,并使用正确的table alias

类似的东西,

table1 INNER JOIN table2 ON (table1.id = table2.id)

确保在group by子句中也包含选择列表的列。

您几乎已经接近编写所需的SQL,只需实现建议即可获得所需的输出。

答案 1 :(得分:0)

如果要从多个表生成结果集绘图,则必须对所涉及的表执行适当的连接。使连接“适当”的原因主要是由连接谓词测量,根据表之间的关系判断。在您的情况下,如果表access_logclient通过各自的id字段相关(这会有点奇怪),那么此查询将完成此任务:

SELECT   
  client.title AS TITLE, 
  COUNT(SUBSTR(activity, INSTR(activity, '/', 1, 4) + 1, INSTR(activity, '/', 1, 5) - INSTR(activity, '/', 1, 4)-1)) AS DOWNLOADS 
FROM
  access_log
  JOIN client
    ON client.id = access_log.id
WHERE
  client.id = 5555
  AND time_stamp BETWEEN TO_DATE ('2014/05/01', 'yyyy/mm/dd') AND TO_DATE ('2014/10/31', 'yyyy/mm/dd') 
GROUP BY SUBSTR(activity, INSTR(activity, '/', 1, 4) + 1, INSTR(activity, '/', 1, 5) - INSTR(activity, '/', 1, 4) -1) 
ORDER BY DOWNLOADS DESC;