0

我从查询中得到这些结果:

乔恩·多伊 63741 | 26.11.2012 11:32:09
Joh Doe 63741 | 06.12.2012 10:30:03

如您所见,第一列是相等的,第二列中的日期不相等。SQL 如下所示:

select name, date from (
    select 
      concat(sfoa.firstname, ' ', sfoa.lastname, ' ', sfoa.postcode) as name,
      sfo.created_at as "date"
          from sales_flat_order sfo join sales_flat_order_address sfoa on sfo.entity_id = sfoa.parent_id where sfoa.address_type = 'shipping' and sfoa.lastname = 'Doe'
  ) d

现在我想按名称对其进行分组,如下所示:

group by name having count(name) > 1

并获取 2 个日期之间的差异。那可能吗?结果应该是这样的:

乔恩·多伊 63741 | 10

可以有超过 2 行,我总是想要结果中的第一行和最后一行。

谢谢!

4

2 回答 2

2

对的,这是可能的。

select name, MAX(date) - MIN(date) as date_diff from (
select 
  concat(sfoa.firstname, ' ', sfoa.lastname, ' ', sfoa.postcode) as name,
  sfo.created_at as "date"
      from sales_flat_order sfo 
      join sales_flat_order_address sfoa 
      on sfo.entity_id = sfoa.parent_id 
      where sfoa.address_type = 'shipping' 
      and sfoa.lastname = 'Doe'
) d
group by name
having count(name) > 1

然后,您可以根据需要格式化日期。

于 2013-02-20T12:55:15.817 回答
0

您可以尝试如下:

select name, date1,date2, datediff(date1,date2) as diff from (
    select 
    concat(sfoa.firstname, ' ', sfoa.lastname, ' ', sfoa.postcode) as name,
    sfo.created_at as "date1"
    from sales_flat_order sfo join sales_flat_order_address sfoa on sfo.entity_id = sfoa.parent_id where sfoa.address_type = 'shipping' and sfoa.lastname = 'Doe'
    ORDER BY sfo.created_at LIMIT 1

    UNION

    select 
    concat(sfoa.firstname, ' ', sfoa.lastname, ' ', sfoa.postcode) as name,
    sfo.created_at as "date2"
    from sales_flat_order sfo join sales_flat_order_address sfoa on sfo.entity_id = sfoa.parent_id where sfoa.address_type = 'shipping' and sfoa.lastname = 'Doe'
    ORDER BY sfo.created_at DESC LIMIT 1
) d

GROUP BY name 
HAVING count(name) > 1

我没有测试它。

于 2013-02-20T12:58:28.050 回答