2

我已经为 SQL Server 查询苦苦挣扎了一段时间,并意识到我必须从比我更了解 SQL Server 的人那里获得帮助。

环境:SQL Server 2008

SELECT      
    t1.SUPPL_ORDERNO, 
    t2.OUR_ORDER,
    t3.CUST_INVOICE
FROM t1 

    LEFT OUTER JOIN t2 
        ON t1.SUPPL_ORDERNO = t2.ORDER_REM5 

    LEFT OUTER JOIN t3
        ON t2.ORDER_REM5  = t3.INV_REM5

GROUP BY t1.SUPPL_ORDERNO, t2.OUR_ORDER, t3.CUST_INVOICE
ORDER BY t1.SUPPL_ORDERNO,t3.CUST_INVOICE

这是我通过上面的查询得到的结果:

SUPPL_ORDERNO                  OUR_ORDER CUST_INVOICE
------------------------------ --------- ------------
143914                         64228     179890
143914                         64228     179935
143914                         64228     179995
143914                         64228     179999
143914                         64228     180067
143914                         64228     180148
326042                                   
326052                         64549     180219
326086                         64633  

CUST_INVOICE我为每个组合得到多个SUPPL_ORDERNOOUR_ORDER但我只想返回最新的CUST_INVOICE(=最大的发票号)。

这是我要返回的结果:

SUPPL_ORDERNO                  OUR_ORDER CUST_INVOICE
------------------------------ --------- ------------
143914                         64228     180148
326042                                   
326052                         64549     180219
326086                         64633   

概括:

  1. 如果组合的数量超过一 (1) CUST_INVOICESUPPL_ORDERNO并且OUR_ORDER我只想显示CUST_INVOICE数量最多的
  2. 如果没有OUR_ORDERCUST_INVOICE我希望它显示为空
  3. 如果有OUR_ORDER并且没有,CUST_INVOICE我希望它显示为空

任何帮助,将不胜感激!

4

2 回答 2

2

从 GROUP BY 中删除 t3.CUST_INVOICE 并将 MAX(t3.CUST_INVOICE) 函数用于 SELECT 语句

SELECT t1.SUPPL_ORDERNO, t2.OUR_ORDER, MAX(t3.CUST_INVOICE) AS CUST_INVOICE
FROM t1 LEFT JOIN t2 ON t1.SUPPL_ORDERNO = t2.ORDER_REM5 
        LEFT JOIN t3 ON t2.ORDER_REM5  = t3.INV_REM5
GROUP BY t1.SUPPL_ORDERNO, t2.OUR_ORDER
ORDER BY t1.SUPPL_ORDERNO, t3.CUST_INVOICE

SQLFiddle上的简单示例

于 2013-01-07T23:42:59.097 回答
1

解决此问题的最佳方法是使用row_number(). 这会为事物添加一个序列号,在本例中是每个订单中的发票号:

select suppl_orderno, our_order, cust_invoice
from (SELECT t1.SUPPL_ORDERNO, t2.OUR_ORDER, t3.CUST_INVOICE,
             row_number() over (partition by t1.SUPPL_ORDERNO, t2.OUR_ORDER order by t3.cust_invoice desc) as seqnum
      FROM t1 LEFT OUTER JOIN
           t2 
           ON t1.SUPPL_ORDERNO = t2.ORDER_REM5 LEFT OUTER JOIN
           t3
           ON t2.ORDER_REM5  = t3.INV_REM5
     ) t
where seqnum - 1
ORDER BY SUPPL_ORDERNO,CUST_INVOICE

通过以降序对发票进行排序,最近的发票将获得值“1”,用于过滤器。

于 2013-01-06T22:01:36.877 回答