我有一个数据如下的要求
ID Date Comments
101 23/Jun/2018 RR: Insufficient resource
101 23/Jun/2018 Next week apply for leave
102 22/Jun/2018 NULL
103 21/Jun/2018 Go ahead
我需要一个Oracle sql才能以上述方式获取以上数据
ID DATE A_comments D_comments
101 23/Jun/2018 Next week apply for leave RR: Insufficient resource
102 22/Jun/2018
103 21/Jun/2018 Go ahead
每当注释带有前缀RR:应添加到D_comments
,而没有前缀RR则应转到A_comments
以获取特定ID。
帮助我实现这一目标。
答案 0 :(得分:0)
此查询适用于您的示例数据。但是,如果Alex提到了其他未知情况,请编辑您的问题以添加它。
SELECT
id,
date_t,
MAX(
CASE
WHEN comments LIKE 'RR:%' THEN NULL
ELSE comments
END
) a_comments,
MAX(
CASE
WHEN comments LIKE 'RR:%' THEN comments
END
) d_comments
FROM
t
GROUP BY
id,
date_t;
答案 1 :(得分:0)
您可以使用CASE
语句根据值“分配”列:
SELECT id,
date,
case when comments not like 'RR:%' then comments end as A_comment,
case when comments like 'RR:%' then comments end as D_comment
FROM my_table;
输出为
ID DATE A_comments D_comments
101 23/Jun/2018 Next week apply for leave
101 23/Jun/2018 RR: Insufficient resource
102 22/Jun/2018
103 21/Jun/2018 Go ahead
因此,您需要将列“折叠”成一行,例如使用MAX
:
SELECT id,
date,
MAX(case when comments not like 'RR:%' then comments end) as A_comment,
MAX(case when comments like 'RR:%' then comments end) as D_comment
FROM my_table
GROUP BY id, date;
会生成
ID DATE A_comments D_comments
101 23/Jun/2018 Next week apply for leave RR: Insufficient resource
102 22/Jun/2018
103 21/Jun/2018 Go ahead
编辑:
要反映您的评论,并添加所有评论,可以使用LISTAGG
代替MAX
:
SELECT id,
date,
LISTAGG(case when comments not like 'RR:%' then comments end, '-'
WITHIN GROUP (ORDER BY comments)) as A_comment,
MAX(case when comments like 'RR:%' then comments end) as D_comment
FROM my_table
GROUP BY id, date;
答案 2 :(得分:0)
尝试以下
WITH t
AS (SELECT 101 id_col,
'23/Jun/2018' date_col,
'RR: Insufficient resource' comments
FROM DUAL
UNION
SELECT 101 id_col,
'23/Jun/2018' date_col,
'Next week apply for leave' comments
FROM DUAL
UNION
SELECT 102 id_col, '22/Jun/2018' date_col, 'NULL' comments FROM DUAL
UNION
SELECT 103 id_col, '21/Jun/2018' date_col, 'Go ahead' comments
FROM DUAL)
( SELECT id_col,
date_col,
MAX (CASE WHEN comments NOT LIKE 'RR:%' THEN comments END)
a_comment,
MAX (CASE WHEN comments LIKE 'RR:%' THEN comments END) d_comment
FROM t
GROUP BY id_col, date_col)
ORDER BY id_col