当有贷记凭证时,我正在尝试检索发票活动的所有行,但付款除外。我们有一个可以有不同活动的通用订单号,例如发票(I),贷项凭证(C),付款(P),借项凭证(D)。如果订单没有Credit备忘录,我不希望它列出。
我正在寻找的结果集是:
Order_id record_type amount order_date invoice_no_string
-------------------------------------------------------------------
5023318 Invoice 3063.38 3/7/16 5023318
5023318 Credit memo -3063.38 3/7/16 5023318
5023318 Invoice 2723.00 3/7/16 5023318A
相反,经过几天试图解决这个问题之后,我明白了这一点:
Order_id record_type amount order_date invoice_no_string
-------------------------------------------------------------------
5023318 Invoice 3063.38 3/7/16 5023318
5023318 Credit memo -3063.38 3/7/16 5023318
5023318 Credit memo -3063.38 3/7/16 5023318
5023318 Invoice 2723.00 3/7/16 5023318A
我是SQL的新手,不知道这是什么数据库类型......
以下是代码,感谢任何帮助..
SELECT
file1.order_id order_id,
file1.invoice_no_string,
file1.bill_date,
convert(varchar(10),orders.ordered_date,101) order_date,
file1.customer_id cust_no,
customer.name cust_name,
file1.record_type type,
file1.amount amount,
file1.source
FROM
open_item file1
JOIN
open_item file2
ON
file1.order_id = file2.order_id
LEFT OUTER JOIN
customer on customer.id = file1.customer_id and
customer.company_id = 'TMS'
LEFT OUTER JOIN
orders on orders.id = file1.order_id and
orders.company_id = 'TMS'
WHERE
file1.company_id = 'TMS' and
orders.ordered_date >= {d '2016-03-01'} and
orders.ordered_date <= {d '2016-03-15'} and
file1.source ='B' and
file1.record_type = 'I' and
file2.record_type = 'C' or
file1.company_id = 'TMS' and
orders.ordered_date >= {d '2016-03-01'} and
orders.ordered_date <= {d '2016-03-15'} and
file1.source ='B' and
file1.record_type = 'C'
ORDER BY
order_id
答案 0 :(得分:0)
对于您想要执行的操作,您的查询似乎过于复杂。对于FROM
子句中的所有不同表,我不清楚您正在寻找的确切过滤。
但是,如果您想要没有信用记录的客户的所有未付款未清项目,那么您可以使用如下查询:
SELECT . . .
FROM open_item ot JOIN
customer c
ON c.id = ot.customer_id and
c.company_id = 'TMS' JOIN
orders o
ON o.id = ot.order_id
WHERE o.ordered_date >= {d '2016-03-01'} AND
o.ordered_date <= {d '2016-03-15'} AND
ot.record_type <> 'P' AND
EXISTS (SELECT 1
FROM order_type ot2
WHERE ot2.customer_id = ot.customer_id AND
ot2.record_type = 'C'
);
除了简化之外,关键的想法是使用EXISTS
来查看同一客户的相应信用记录。