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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配