【问题标题】:how to SELECT and Concat() column values based on several conditions SQL query?如何根据多个条件 SQL 查询 SELECT 和 Concat() 列值?
【发布时间】:2015-10-22 23:53:02
【问题描述】:

这里是 SQL 的新手。所以我有两张表,我们以下面的两张表为例。

表 A

set_num   s_id   s_val
100        3      AA 
100        5      BB
200        3      AA
200        9      CC

表 B

s_id    s_val    phrase        seq 
1        DD      'hi'         'first'
3        AA      'hello'      'first'
6        EE      'goodnight'  'first'
5        BB      'world'      'second'
9        CC      'there'      'second'
4        FF      'bye'        'first'

我想在两列上将表 A 与表 B 连接起来,例如复合键 (s_id, s_val),我想返回 set_num 来自表 A 和表 B 中的短语连接(我们将其称为 entire_phrase,concat(...) AS whole_phrase)。 连接也应该遵循连接短语的顺序。这将由表 B 中每个短语的 seq 列确定。 “First”表示这个短语需要先出现,“Second”表示接下来出现。我想用一个 SELECT 查询来做到这一点,但不确定这是否可能没有变得复杂。我可以在 SELECT 中执行此操作还是需要其他方法?

预期输出:

set_num    entire_phrase
100        'hello world'
200        'hello there'

不是

set_num    entire_phrase
100        'world hello'
200        'there hello'

任何帮助/方法将不胜感激!

【问题讨论】:

  • 您是否保证每个set_num 都有两条记录,在表 A 中一个标记为“第一”,另一个标记为“第二”?
  • 3 种不同的 RDBMS 真的需要它吗?
  • 在 mysql 中使用 group_concat() 很容易。
  • 对不起。不应包含 Mysql,因为这是针对 db2 的。 @PMy77-1。我被告知这是肯定的,每组我会有固定数量的记录,每个记录都有一个独特的值来确定哪个先出现。 ..等等

标签: mysql sql db2 concat jointable


【解决方案1】:

你可以这样做:

select temp1.set_num, concat(phrase1,' ',phrase2) as entire_phrase
from (
(
select set_num, b.phrase as phrase1
from TableA as A
join TableB as B
on a.s_id = b.s_id 
and a.s_val = b.s_val 
and b.seq = 'first'
) as temp1
join 
(
select set_num, b.phrase as phrase2 
from TableA as A
join TableB as B
on a.s_id = b.s_id 
and a.s_val = b.s_val 
and b.seq = 'second' 
) as temp2
on temp1.set_num = temp2.set_num
) 

在这里运行:http://sqlfiddle.com/#!9/d63ac3/1

【讨论】:

  • 谢谢你。我会试一试,让你知道。 Qq...如果每个集合可以有不同数量的短语,那么只有额外的连接?
  • 是的,假设所有都是强制性的。此外,如果有更多,会有更好的方法来解决它。我只是在这里“相当容易理解”。
猜你喜欢
  • 1970-01-01
  • 2022-11-14
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
相关资源
最近更新 更多