0

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

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 列使用单个选择以提高性能?

4

1 回答 1

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

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

于 2012-09-04T20:37:08.133 回答