【问题标题】:SQL joins with order bySQL 以 order by 连接
【发布时间】:2014-04-19 07:02:02
【问题描述】:

我有两张桌子

table 1
col1 date
1    13/4/2014
2    15/4/2014
3    17/4/2014
5    19/4/2014

table 2
col1 date
1    13/4/2014
3    16/4/2014
6    18/4/2014

joining the two tables i should get

col1 date       col2 date
1    13/4/2014  1    13/4/2014
2    15/4/2014
3    17/4/2014  3    16/4/2014
                6    18/4/2014
5    19/4/2014

重要的是date 列应该按照col 数据65 所见的那样进行排序。 这可能吗?

编辑: 决赛桌需要按col1.datecol2.date 排序,这样col1col2 中的较早日期将在连接表中排序18/4/2014 将排在19/4/2014 之前,即使它们在不同的位置列。我希望我的观点很清楚。 谢谢 编辑:

table 1
1, "2014-04-03" 
2, "2014-04-04"
3, "2014-04-11"
4, "2014-04-16"
5, "2014-04-04"
6, "2014-04-17"
7, "2014-04-17"

table 2
1, "2014-04-04"
2, "2014-04-11"
5, "2014-04-17"

编辑:加入后应该是这样的

1 2014-04-03 
2 2014-04-04 
5 2014-04-04 1 2014-04-04
3 2014-04-11 2 2014-04-11
4 2014-04-16 
6 2014-04-17
7 2014-04-17 5 2014-04-17

【问题讨论】:

  • 嗯,我们可以为您的新数据获取预期结果表吗?

标签: sql postgresql join postgresql-9.1


【解决方案1】:

SQL Fiddle

select col1, date1, col2, date2
from
    t1
    full outer join
    t2 on col1 = col2
order by coalesce(date1, date2), date2;

【讨论】:

  • 您可能需要更改为coalesce(least(date1, date2), date1, date2)。否则(12/4/2014 12/4/2014) 将在(13/4/2014 11/4/2014) 之前
  • @clodoaldo:它没有显示正确的结果。sqlfiddle.com/#!15/9a646/1/0
  • @IgorRomanchenko:它不工作检查你的 sql 的小提琴。谢谢
【解决方案2】:
select n.col1
     , n.date1
     , m.col2
     , m.date2
from t1 n 
full join t2 m on n.date1 = m.date2
              and n.col1 = (select max(col1) from t1 where date1 = m.date2 )  
              and n.col1 is not null
where n.date1 is not null or m.date2 is not null
order by coalesce(n.date1, m.date2)
       , coalesce(n.col1, m.col2)

SQLFiddle with new data

SQLFiddle with old data

【讨论】:

  • 加入不是问题。按 col1 排序,col2 不会给出预期的结果。请注意 col2 数据 6 在 col1 数据 5 之前,因为 6 的日期更早。我需要在连接表中按日期对数据进行排序。
  • @user1572215 :您的意思是它们应该按两列中的 MAX(date) 排序吗?
  • 是的,这就是我想要实现的。请看上面的编辑
  • 我已经发布了一组新的数据,这对它不起作用。感谢您的尝试。
  • 呃还是不行,检查左边,未排序
【解决方案3】:

幸运的是,PostgeSQL 有一个很棒的函数,叫做LEAST();查询很简单:

SELECT col1, date1, col2, date2
FROM t1
FULL OUTER JOIN t2
             ON col1 = col2
ORDER BY LEAST(date1, date2), GREATEST(date1, date2)

fiddle for dataset 1fiddle for dataset 2)。


已编辑

添加了GREATEST() 的使用,然后按其他值排序。

【讨论】:

  • 啊,我想我明白您指的是什么(您真的需要更具体地说明问题所在)。 3、2、1 中的新版本...
猜你喜欢
  • 2018-05-26
  • 2013-10-15
  • 2021-12-28
  • 1970-01-01
  • 2015-05-21
  • 1970-01-01
  • 2016-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多