我有一些表具有以下结构。
表1
s_cd p_cd c_cd record
ABC ALL DEF Comment-
ABC ALL GHI Comment-
QWE RTY UIO Comment
表2
type title
AA Ants
BB Bees
CC Cats
我正在寻找能够根据特定规则产生输出的解决方案,如果表1的 p_cd 为 ALL ,那么我们需要从表2中获取所有类型并附加到注释 - ,并为每个类型替换 p_cd 。如果这听起来令人困惑,请查看表格以便更好地理解。
s_cd p_cd c_cd record
ABC AA DEF Comment-AA
ABC BB DEF Comment-BB
ABC CC DEF Comment-CC
ABC AA GHI Comment-AA
ABC BB GHI Comment-BB
ABC CC GHI Comment-CC
QWE RTY UIO Comment
答案 0 :(得分:2)
用两组来考虑数据。
第一组是“ALL”,第二组是 NOT “ALL”
在第一组交叉连接到table2(将table1中所有记录的组合返回到table2中的所有记录。由于我们知道table2中的每条记录都需要table2中的所有记录,因此我们需要交叉连接生成必要的数据)。在第二组中没有交叉连接,因为我们从第一个表中获得了所有需要的信息。
SELECT T1.S_CD, T2.Type as P_CD, T1.C_CD, concat(T1.Record, T2.Title) as Record
FROM Table 1 T1
CROSS JOIN Table2 T2
WHERE T1.P_CD = 'ALL'
UNION ALL
SELECT T1.S_CD, T1.P_CD, T1.C_CD, T1.Record
FROM Table 1 T1
WHERE T1.P_CD <> 'ALL'
答案 1 :(得分:1)
试试这个:
WITH
-- input, don't use in final query
table_1(s_cd,p_cd,c_cd,record) AS (
SELECT 'ABC','ALL','DEF','Comment-'
UNION ALL SELECT 'ABC','ALL','GHI','Comment-'
UNION ALL SELECT 'QWE','RTY','UIO','Comment'
)
,
table_2(type,title) AS (
SELECT 'AA','Ants'
UNION ALL SELECT 'BB','Bees'
UNION ALL SELECT 'CC','Cats'
)
-- end of input
SELECT
s_cd
, type AS p_cd
, c_cd
, record||type AS record
FROM table_1
JOIN table_2 ON p_cd='ALL'
UNION ALL
SELECT
*
FROM table_1
WHERE p_cd !='ALL'
ORDER BY 1
;
答案 2 :(得分:1)
Select Table1.s_cd,
Case when Table2.type is not null then Table2.type else table1.p_cd end as p_cd,
Table1.c_cd, Case when Table1.p_cd='ALL' then Table1.record + table2.type else Table1.record end as record
from Table1 left outer join Table2 on Table1.p_cd='All'