SQL - 连接 2 个表并返回 2 行之间的值差异
Posted
技术标签:
【中文标题】SQL - 连接 2 个表并返回 2 行之间的值差异【英文标题】:SQL - Join 2 tables and also return difference in value between 2 rows 【发布时间】:2021-11-05 00:21:55 【问题描述】:我正在尝试返回具有各种条件(搜索词、日期等)的产品列表,并且我有以下示例 SQL。
SELECT *
FROM products
JOIN ( SELECT date, price, product_id
FROM pricing
WHERE id IN ( (SELECT MAX(id)
FROM pricing
GROUP BY product_id ) )
AND date = '2021-09-08' ) as current_price on products.id=price.product_id
WHERE 1
AND sku like '%%'
OR title like '%%'
ORDER BY id ASC
它从 2 个表中提取数据:产品和定价。
产品
+----+----------------+--------+
| id | title | sku |
+----+----------------+--------+
| 1 | Product Name 1 | 654987 |
| 2 | Product Name 2 | 548879 |
| 3 | Product Name 3 | 541685 |
+----+----------------+--------+
定价
+----+------------+------------+-------+
| id | product_id | date | price |
+----+------------+------------+-------+
| 1 | 1 | 06-09-2021 | 1.99 |
| 2 | 2 | 06-09-2021 | 1.99 |
| 3 | 1 | 07-09-2021 | 3.99 |
| 4 | 3 | 06-09-2021 | 5.99 |
| 5 | 3 | 08-09-2021 | 6.99 |
| 6 | 1 | 08-09-2021 | 6.99 |
+----+------------+------------+-------+
期望的输出
+----+----------------+--------+---------------+-------------------+------------+
| id | title | sku | current_price | last_price_update | difference |
+----+----------------+--------+---------------+-------------------+------------+
| 1 | Product Name 1 | 654987 | 6.99 | 08-09-2021 | 2.5 |
| 2 | Product Name 2 | 548879 | 1.99 | 06-09-2021 | 0 |
| 3 | Product Name 3 | 541685 | 6.99 | 08-09-2021 | -1 |
+----+----------------+--------+---------------+-------------------+------------+
我的问题是我也想返回一个差异列,显示最新价格与之前的价格之间的差异。
我已经尝试了十亿次,但 SQL 不是我的菜,我要么返回完整的价格列表,要么什么都不返回。
使用 MariaDB 版本:10.3.30
谢谢, 阿什利
【问题讨论】:
精确的 mysql 版本是...?以 CREATE TABLE + INSERT INTO(或创建在线小提琴)的形式提供示例数据,并提供此数据的所需输出并附上解释。 【参考方案1】:您可以使用row_number()
枚举价格,然后条件聚合得到两个价格:
select p.*, pr.current_price, pr.previous_price,
(pr.current_price - pr.previous_price) as diff
from products p join
(select product_id,
max(case when seqnum = 1 then price end) as current_price,
max(case when seqnum = 2 then price end) as previous_price
from (select pr.*,
row_number() over (partition by product_id order by date desc) as seqnum
from pricing pr
) pr
where seqnum <= 2
group by product_id
) pr
on pr.product_id = p.id;
【讨论】:
以上是关于SQL - 连接 2 个表并返回 2 行之间的值差异的主要内容,如果未能解决你的问题,请参考以下文章