从大子查询中获取多个列

时间:2012-09-04 19:51:16

标签: sql oracle ansi-sql

我看到一些关于从子查询获取列的帖子,其中大多数建议对每列使用一个选择,但这是我的情况

SELECT CAST(p.idvendor AS VARCHAR(10)), CAST(p.description AS VARCHAR(50)),  
(SELECT CAST(NVL(SUM(CASE WHEN locals_sales.cantidad >=0
                           AND locals_sales.cantidad <locals_sales.pqlocals
                     THEN 1 ELSE 0 END), '0') AS VARCHAR(10)) 
   FROM locals_sales, agents, vendors, locals, locals_sales, history
  WHERE locals.idvendor = vendors.idvendor 
    AND locals_sales.IDlocals = locals.idlocals
    AND agents.codagente=vendors.codagente
    AND agents.idagent!=1
    AND locals_sales.number_n_line = locals_sales.n_line
    AND locals.estado=1
    AND vendors.idvendor = p.idvendor
    AND history.number_line(+) = locals_sales.n_line
    AND history.date(+) >= to_date('4/9/2012 00:00', 'dd/mm/yy HH24:mi:ss')
 ) AS critic, 
(SELECT CAST(NVL(SUM(CASE WHEN locals_sales.cantidad >=locals_sales.pqlocals
                           AND locals_sales.cantidad <locals_sales.media
                     THEN 1 ELSE 0 END), '0') AS VARCHAR(10))
   FROM locals_sales, agents, vendors, locals, locals_sales, history
  WHERE locals.idvendor = vendors.idvendor
    AND locals_sales.IDlocals = locals.idlocals
    AND agents.codagente=vendors.codagente
    AND agents.idagent!=1
    AND locals_sales.number_n_line = locals_sales.n_line
    AND locals.estado=1
    AND vendors.idvendor = p.idvendor
    AND history.number_line(+) = locals_sales.n_line
    AND history.date(+) >= to_date('4/9/2012 00:00', 'dd/mm/yy HH24:mi:ss')
 ) AS medium, 
(SELECT CAST(NVL(SUM(CASE WHEN locals_sales.cantidad >=locals_sales.media
                     THEN 1 ELSE 0 END), '0') AS VARCHAR(10))
   FROM locals_sales, agents, vendors, locals, locals_sales, history
  WHERE locals.idvendor = vendors.idvendor
    AND locals_sales.IDlocals = locals.idlocals
    AND agents.codagente=vendors.codagente
    AND agents.idagent!=1
    AND locals_sales.number_n_line = locals_sales.n_line
    AND locals.estado=1
    AND vendors.idvendor = p.idvendor
    AND history.number_line(+) = locals_sales.n_line
    AND history.date(+) >= to_date('4/9/2012 00:00', 'dd/mm/yy HH24:mi:ss')
 ) AS NORMAL 
 FROM vendors p, agents ag
WHERE ag.codagente=p.codagente

正如您所看到的,每列有三个SUM,这些列来自相同的表,不同之处在于每个选择的每个CASE中的前置条件

此外,几乎每个选择的结尾我都将此作为条件

vendors.idvendor = p.idvendor

p是子查询

之外的表的别名

如何避免使用几乎相似的三个选项,而是使用3列的单个选择来提高性能?

1 个答案:

答案 0 :(得分:1)

您可以通过将子查询移动到FROM子句并进行正确连接来处理此问题。

最终查询如下:

select CAST(p.idvendor AS VARCHAR(10)), CAST(p.description AS VARCHAR(50)),
       s.val1, s.val2, sl.val3
from vendors p join
     agents ag 
     on p.codeagent = ag.codeagent join
     (<a variation of your subquery here with all three columns defined and idvendor in the select list>
     ) s
     on p.idvendors= s.idvendor

另外,为了使您的查询更具可读性,您应该使用正确的连接语法。