0

I have customers with contract at various sites which must be charged.

There are two types of billing address for the sites: sites charged at the customer's address and sites charged to another address. The kind of site is handled by the field 'status': if the site is charged at the customer's address, the field is equal to 'C'. If it is charged to a different site's address, it is equal to 'A' and the field 'bill_site_id' is filled with the 'site_id' used for billing. I want to retrieve, in one query, the address where I have to send the bill...

Let's say a customer have two sites (the A refers to the B for billing); the request obviously shows the two sites, but I only want the one used for billing (the B). How to retrieve this one only?

Here is my query (anonymized, so please be gentle :-) )

SELECT CASE wp.status
      WHEN 'A'
         THEN wp2.name
      ELSE c.NAME
   END AS NAME,
   CASE wp.status
      WHEN 'A'
         THEN wp2.adress
      ELSE c.street
   END AS street,
   CASE wp.status
      WHEN 'A'
         THEN wp2.city
      ELSE c.city
   END AS city,
   CASE wp.status
      WHEN 'A'
         THEN wp2.postcode
      ELSE c.postcode
   END AS postcode
FROM customer c, site wp, site wp2, customer_site cwp
WHERE c.idcompany = cwp.idcompany
    AND cwp.site_id = wp.site_id
    AND wp2.site_id(+) = wp.bill_site_id
    AND c.idcompany = :someId
GROUP BY wp.status,
     wp2.name,
     wp2.adress,
     wp2.city,
     wp2.postcode
4

2 回答 2

0

我很确定我知道您想要什么,但不是 100% 确定查询中的“ch.status”指的是什么。另外,我不确定从提供的信息中您能否实现您想要的...

希望数据结构在您的控制之下,以便您可以根据需要进行设置。

如果我正确阅读了您的规范,那么我认为您只需要/需要查询中的站点表的 1 个实例,但是不清楚您如何识别客户的地址。

解决此问题的一种方法是让站点表具有 main_address 标志。(我认为这是围绕 ch.status 的困惑)

如果站点表上有一个标志,那么...

WHERE c.idcompany = cwp.idcompany AND cwp.site_id = wp.site_id AND ((C.STATUS = 'C' AND WP.MAIN_ADDRESS = 1) OR (C.STATUS = 'A' AND WP.SITE_ID = C.BILL_SITE_ID ) )

另一种方法是将主要地址和帐单地址作为客户表上的外键,并忘记状态标志:

WHERE WP.SITE_ID = 解码(C.BILLING_ADDRESS,NULL,C.MAIN_ADDRESS,C.BILLING_ADDRESS)

如果这没有意义,那么也许您可以发布所涉及表的 DESCRIBE。

于 2011-09-01T15:57:42.643 回答
0

从技术上讲,联合是两个查询,但您可以在一个命令中运行它,它应该做您想做的事情,所以我将它作为一个选项扔掉。:)

SELECT c.Name AS NAME, c.street AS STREET, c.city AS CITY, c.postcode AS postcode
FROM customer c
INNER JOIN customer_site cwp ON c.idcompany = cwp.idcompany
INNER JOIN site wp ON cwp.site_id = wp.site_id
WHERE c.idcompany = :someid AND wp.status = 'C'
UNION
SELECT wp2.name AS NAME, wp2.adress AS STREET, wp2.city AS CITY, wp2.postcode AS postcode
FROM customer c
INNER JOIN customer_site cwp ON c.idcompany = cwp.idcompany
INNER JOIN site wp ON cwp.site_id = wp.site_id
INNER JOIN site wp2 ON wp.bill_site_id = wp2.site_id
WHERE c.idcompany = :someid AND wp.status = 'A'

我看不到您的表结构,因此可能可以进行更多优化,但我认为这将有助于为您指明工作方向。这可能不会比您现有的查询更快,但它更容易理解。

于 2011-09-01T16:40:03.987 回答