【问题标题】:How to join 2 table on max record but show all records of the first table?如何在最大记录上加入 2 个表但显示第一个表的所有记录?
【发布时间】:2021-10-06 08:25:00
【问题描述】:

Table Order 有订单号、行号和金额。订单上可以有多行。表运费对每个订单都有运费。 如何连接两个表,以便将运费添加到订单表的最大行? 所以基本上运费只添加一次,而不是像左连接那样在订单表的每一行上添加。

OL

Select ol.orderno , ol.ordersuf, ol.lineno_ , ol.amount
from order ol 
where ol.orderno= 12345

[

广告

select ad.orderno, ad.ordersuf , ad.freight
from Freight ad
where ad.orderno =12345

[

预期结果:

[

【问题讨论】:

  • 输入或粘贴数据,而不是图像。不要使用为您创建示例数据。

标签: sql join select subquery outer-join


【解决方案1】:
SELECT 
  a.orderno, 
  a.ordersuf, 
  a.lineno_, 
  a.amount, 
  CASE WHEN a.lineno_ = Max(a.lineno_) OVER(partition BY a.orderno) THEN b.freight ELSE 0 END AS freight 
FROM 
  ol a 
  INNER JOIN freight b ON a.orderno = b.orderno

【讨论】:

  • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票。
【解决方案2】:

请尝试以下方法: CASE 语句的语法可能因您的数据库而异。

SELECT ol.orderno , ol.ordersuf, ol.lineno_ , ol.amount, CASE
    WHEN ol.lineno_ = (SELECT max(sol.lineno_) FROM order sol WHERE sol.orderno = ol.orderno) THEN ad.freight
    ELSE 0
END AS QuantityText FROM order ol INNER JOIN Freight ad WHERE ol.orderno = ad.orderno

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 2019-08-30
    • 2023-03-20
    • 2020-08-12
    • 1970-01-01
    相关资源
    最近更新 更多