【问题标题】:MySQL self join but in the same rowMySQL 自连接但在同一行
【发布时间】:2022-01-17 02:06:49
【问题描述】:

我有这张桌子:

date sku note
11/12 123 note
11/13 123 note
11/12 456 note
11/13 456 note
11/12 789 note
11/13 789 note

(注是随机的) 我希望结果返回这个:

date sku note sku note sku note
11/12 123 note 456 note 789 note
11/13 123 note 456 note 789 note

我尝试了自我加入

select * from schedules a, schedules b 
where a.date = b.date;

但这就是我得到的:

date sku note sku
11/12 123 note 456
11/12 123 note 789
11/13 123 note 456
11/13 123 note 789

【问题讨论】:

  • 请问,您能否提供更多关于为什么需要自加入的信息?
  • 哪个版本的mysql?
  • 搜索 mysql pivot - 这是一个很常见的问题,有很多东西可以找到。
  • @LukStorms 版本 8.0.18
  • @Faesal 我不必使用自联接,但这正是我发现的,所以我认为可以使用它来完成?

标签: mysql sql


【解决方案1】:

计算一个row_number,然后旋转。

select `date`
, max(case when rn = 1 then sku end) as sku1
, max(case when rn = 1 then note end) as note1
, max(case when rn = 2 then sku end) as sku2
, max(case when rn = 2 then note end) as note2
, max(case when rn = 3 then sku end) as sku3
, max(case when rn = 3 then note end) as note3
from
(
    select `date`, sku, note
    , row_number() over (partition by `date` order by sku) as rn
    from schedules 
) q
where rn <= 3
group by `date`
order by `date`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    • 2013-04-23
    • 1970-01-01
    • 2011-10-15
    • 2018-01-05
    • 1970-01-01
    相关资源
    最近更新 更多