【问题标题】:Join 2 tables to produce desired output加入 2 个表以产生所需的输出
【发布时间】:2022-01-07 00:03:23
【问题描述】:

我有 2 个表如下:

产品表:

ProductID   Name
   1        Condensed cheese
   2        Milk       

价格表:

ProductID   Currency   Price
    2          EUR       1.50
    2          USD       1.74
    2          JPY     194.624
    1          EUR       0.99
    1          USD       1.15

我正在学习 SQL,想知道将上面的 2 个表连接起来以产生此输出的 SQL 语句是什么:

ProductID     Name               EUR     USD     JPY
    1         Condensed cheese   0.99    1.15    NULL
    2         Milk               1.50    1.74    194.624

【问题讨论】:

  • 这样组织数据通常称为“数据透视”。

标签: mysql sql


【解决方案1】:

你可以使用 max() 函数与 case when

select t1.ProductID ,t1.Name,
 max(case when t2.Currenc= 'EUR' then Price end) as EUR,
 max(case when t2.Currenc= 'USD' then Price end) as USD,
 max(case when t2.Currenc= 'JPY' then Price end) as JPY
 from 
Products t1 join Prices  t2 on t1.ProductID =t2.ProductID  
group by t1.ProductID ,t1.Name   

【讨论】:

  • 感谢您的回答,很抱歉无法接受超过 1 个回答。 Madhur Bhaiya 的回答对解释更有帮助,我赞成你的回答!
  • @meteorzeroo 谢谢你可以接受任何你认为更好的答案。但是您接受的答案不是 ansi sql,我的答案将适合任何后面跟着 ansi sql 的 db。聚合函数不适用于 NULL,但他提到 :) 如果您认为这更好,您可以关注他
【解决方案2】:

这是一个Pivot Table problem。您将需要使用带有Group By 子句的条件聚合。

  • 使用ProductID 在两个表之间执行Inner Join
  • 我们在 ProductIdName 上执行 Group By,因为您希望 productid 在同一行中包含所有价格。
  • 现在,我们将使用条件函数If() 来确定特定货币列的价格。如果货币代码与该列匹配,我们会考虑该价格值,否则我们会考虑null。因此,例如,在别名为EUR 的列中,我们将拥有其他货币(欧元除外)的null 值。然后我们将使用Max() 函数来确保我们只考虑相应的货币价格。
  • 如果Prices 表中没有特定货币的价格值,则它应为null 值(所有货币将显示nullMax(null, null, ...) = null
  • 最终我们Order By ProductID ASC 通过ProductID 得到结果sorted in ascending order

尝试以下查询:

SELECT pdt.ProductID, 
       pdt.Name, 
       MAX( IF(prc.Currency = 'EUR', prc.Price, NULL) ) AS EUR, 
       MAX( IF(prc.Currency = 'USD', prc.Price, NULL) ) AS USD, 
       MAX( IF(prc.Currency = 'JPY', prc.Price, NULL) ) AS JPY
FROM Products AS pdt 
INNER JOIN Prices AS prc ON prc.ProductID = pdt.ProductID 
GROUP BY pdt.ProductID, pdt.Name 
ORDER BY pdt.ProductID ASC 

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    相关资源
    最近更新 更多