如何根据SELECT和SQL几个条件查询Concat()列的值?
how to SELECT and Concat() column values based on several conditions SQL query?
这里是 SQL 的新手。所以我有两个表,我们以下面两个表为例
Table一个
set_num s_id s_val
100 3 AA
100 5 BB
200 3 AA
200 9 CC
Table 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'
我想在两列上加入 Table A 和 Table B,就像一个复合键(s_id、s_val),我想 return
set_num 来自 Table A 和 Table B 中的短语串联(我们称之为 entire_phrase, concat(...) AS entire_phrase).
连接还应遵循短语连接的顺序。这将由每个短语的 Table 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'
任何 help/approach 将不胜感激!
你可以这样做:
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
)
这里是 SQL 的新手。所以我有两个表,我们以下面两个表为例
Table一个
set_num s_id s_val
100 3 AA
100 5 BB
200 3 AA
200 9 CC
Table 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'
我想在两列上加入 Table A 和 Table B,就像一个复合键(s_id、s_val),我想 return set_num 来自 Table A 和 Table B 中的短语串联(我们称之为 entire_phrase, concat(...) AS entire_phrase). 连接还应遵循短语连接的顺序。这将由每个短语的 Table 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'
任何 help/approach 将不胜感激!
你可以这样做:
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
)