doudui1850 2018-02-09 17:10
浏览 788
已采纳

SQL JOIN表,其中有多个相同id的实例

I have two tables within the same database; tableA has the date I need while tableB has the cost. These tables are like an archive of changing dates and costs so a single item is repeated multiple times but I only want the most recent date and lowest cost.

Data example:

tableA

  LocalSKU: aaa-aaa1 date: 12/1/1
  LocalSKU: aaa-aaa1 date: 11/1/3
  LocalSKU: aaa-aaa1 date: 10/2/1

tableB

  SKU: aaa-aaa1 cost: 0.15
  SKU: aaa-aaa1 cost: 5
  SKU: aaa-aaa1 cost: 0

Desired result:

SKU: aaa-aaa1 date: 12/1/1 cost: 0

I've tried a simple query to pull back a single result with this query:

SELECT MAX(date) 
FROM tableA 
WHERE LocalSKU = (SELECT MIN(cost) 
                  FROM tableB 
                  WHERE SKU = tableB.LocalSKU GROUP BY SKU);

which yielded 0 results.

I'm new to subquerying and joining, is there a single query that can be made to get the desired result? I'm able to get the information I want in separate queries, but I got stuck trying to merge the arrays to combine the desired information.

Help is much appreciated!

  • 写回答

1条回答 默认 最新

  • duanba5777 2018-02-09 17:15
    关注

    Join the tables and use the aggregation function on the result.

    SELECT a.localsku, MIN(cost), MAX(date)
    FROM tableA
    JOIN tableB ON a.localsku = b.sku
    GROUP BY a.localsku
    

    Actually, it will probably be more performant to do the grouping first and then join the subqueries, since joining large tables is expensive.

    SELECT a.localsku, a.date, b.cost
    FROM (
        SELECT localsku, MAX(date) AS date
        FROM tableA
        GROUP BY localsku) AS a
    JOIN (
        SELECT sku, MIN(cost) as cost
        FROM tableB
        GROUP BY sku) AS b
    ON a.localsku = b.sku
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度