简体   繁体   English

mysql在一行中显示多行

[英]mysql display multiple rows in one row

I have a table tbl_usi in mysql with records as below: 我在mysql中有一个表tbl_usi,记录如下:

present_date    usi_value    deal_count    
----------------------------------------------------------
2015-10-13      b1              c1           
2015-10-12      b2              c2             
2015-10-11      b3              c3

I want to write a query that will do this using present_date field to select the present date and the date before it and display them together: 我想编写一个查询,将使用present_date字段执行此操作,以选择当前日期和之前的日期,并将它们一起显示:

present_date    usi_value    deal_count    previous_date   previous_usi_value   previous_deal_count       
----------------------------------------------------------
2015-10-13      b1              c1         2015-10-12      b2                   c2         
2015-10-12      b2              c2         2015-10-11      b3                   c3          
2015-10-11      b3              c3         2015-10-10      b4                   c4

How do I achieve this. 我该如何实现。 Thanks 谢谢

Select everything from your table, then join it to itself, making sure the 2 joined tables are given different names so you can distinguish them (I used 'a' and 'b' here). 从表中选择所有内容,然后将其连接到自身,确保为2个连接的表指定了不同的名称,以便您可以区分它们(我在这里使用了“ a”和“ b”)。 The join offsets the dates by 1 day. 联接使日期偏移1天。 Then you can select the fields you want from the joined table. 然后,您可以从联接表中选择所需的字段。

select 
  a.present_date, 
  a.usi_value, 
  a.deal_count, 
  b.present_date as previous_present_date, 
  b.usi_value as previous_usi_value, 
  b.deal_count as previous_deal_count 
from
  tbl_usi as a 
  left join tbl_usi as b
    on b.present_date = a.present_date - interval 1 day;

If you didn't already have one before, you will now want an index for the present_date column too BTW. 如果您以前还没有,那么现在也要为present_date列创建索引。

Alternative, which works when there are date gaps. 替代方法,当有日期间隔时起作用。

select
  a.present_date, 
  a.usi_value, 
  a.deal_count, 
  b.present_date as previous_present_date, 
  b.usi_value as previous_usi_value, 
  b.deal_count as previous_deal_count 
from
  tbl_usi as a 
  join tbl_usi as b
where
  b.present_date = (select max(present_date) from tbl_usi where present_date < a.present_date);

As with previous solution the same table is joined twice, but this time the previous row is found by way of a subquery. 与以前的解决方案一样,同一张表被连接了两次,但是这次是通过子查询找到前一行的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM