简体   繁体   English

SQL - 复杂的 SQL 查询

[英]SQL - Complicated SQL query

I have two tables;我有两张桌子; the first one is order with columns doc_num, doc_type, doc_tttc , and the second one is order details with columns doc_num, doc_origi, art_code, art_des, qte, price - see below:第一个是order与列doc_num, doc_type, doc_tttc ,而第二个是order details的列doc_num, doc_origi, art_code, art_des, qte, price -见下图:

截屏

Clarification: order with DAC type is order taken by the client and the order with DAA type is order taken by the supervisor is the same order in some cases but the supervisor can change the amount 'QTE' or the item 'ART_CODE' for that's way I want to show as result:说明:DAC 类型的订单是客户接受的订单,DAA 类型的订单是主管接受的订单在某些情况下是相同的订单,但主管可以为此更改数量“QTE”或项目“ART_CODE”我想显示结果:

DAC-19001    DAA-19001  1200    1500

 ART3         ART3        1      300

Welcome to S/O.欢迎来到 S/O。 Not sure exactly what your intent / need is, but maybe this will help.不确定您的意图/需求究竟是什么,但也许这会有所帮助。 Since your order table has the detail totals already aggregated, you probably need to join based on their being a match to a supervisor order by the original document number.由于您的订单表已经汇总了详细信息总计,因此您可能需要根据原始文档编号与主管订单的匹配情况来加入。

Not sure why the "ART3" values were coming along from details... no basis of why one record vs another on that field.不知道为什么“ART3”值来自细节......没有依据为什么该字段上的一个记录与另一个记录。

However, here is what I have.但是,这就是我所拥有的。 The primary query from the order table gets orders.来自订单表的主要查询获取订单。 No problem.没问题。 Then, a LEFT-JOIN means look IF there is a record that matches based on the join criteria.然后,LEFT-JOIN 表示查看是否有基于连接条件匹配的记录。 In this inner "od" result alias query, I am getting distinct original document orders and corresponding supervisor order just for the ID reference.在这个内部“od”结果别名查询中,我得到了不同的原始文档订单和相应的主管订单,仅用于 ID 参考。 Then, if so found, re-joining back to the order table to get ITS total amount by that document number.然后,如果找到,则重新加入订单表以通过该文档编号获取 ITS 总金额。 I could have also done an aggregation of the details and skipped the last left-join.我也可以汇总细节并跳过最后一个左连接。 This could also get the last ART code, but since no ID, record ID, "last record" basis, I would just leave that part alone for now.这也可以获得最后的 ART 代码,但由于没有 ID、记录 ID、“最后一条记录”的基础,我现在只留下那部分。

select
      o.Doc_Num,
      o.Doc_Type,
      o2.Doc_Num as Supervisor_Doc_Num,
      o.Doc_TTC as OriginalOrderTotal,
      o2.Doc_TTC as SupervisorOrderTotal,
      o2.Doc_TTC - o.Doc_TTC as OrderDifference
   from
      Order o
         LEFT JOIN 
         ( select distinct 
                 Doc_OrigI,
                 Doc_Num
              from 
                 Order_Details ) od
            on o.Doc_Num = od.Doc_OrigI
            LEFT JOIN Order o2
               on od.Doc_Num = o2.Doc_Num

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM