我有一个数据表
-----------------------------------------------------------------------------
CUSTOMER CSAC CIRCUIT VALUE TOWN POST_CODE
-----------------------------------------------------------------------------
RCE | CSAC125896 | ICUK809605 | 100 MBPS | BASILDON | SS15 5FS
RCE | CSAC125896 | ICUK809605 | 100 MBPS | BASILDON | SS15 6AA
如果csac值与此相同,我希望第二个邮政编码也显示在同一行
-----------------------------------------------------------------------------
CUSTOMER CSAC CIRCUIT VALUE TOWN POST_CODE POST_CODE2
-----------------------------------------------------------------------------
RCE|CSAC125896 |ICUK809605 |100 MBPS | BASILDON | SS15 5FS | SS15 6AA
我怎样才能达到这个效果。我试过使用转置,但没有得到理想的结果。
答案 0 :(得分:1)
假设您可以拥有两个以上具有相同字段值但行不同的POST_CODE的行,则无法事先知道查询需要返回的列数。
采用略有不同的方法,您可以尝试:
select CUSTOMER, CSAC, CIRCUIT, VALUE, TOWN,
listagg(POST_CODE, ', ') within group (order by post_code)
from your_table
group by CUSTOMER, CSAC, CIRCUIT, VALUE, TOWN
答案 1 :(得分:1)
SELECT CUSTOMER,
CSAC,
CIRCUIT,
VALUE,
TOWN,
MAX( CASE RN WHEN 1 THEN POST_CODE END ) AS POST_CODE_1,
MAX( CASE RN WHEN 2 THEN POST_CODE END ) AS POST_CODE_2
FROM (
SELECT t.*,
ROW_NUMBER() OVER (
PARTITION BY CUSTOMER, CSAC, CIRCUIT, VALUE, TOWN
ORDER BY POST_CODE
) AS RN
FROM table_name t
)
GROUP BY CUSTOMER,
CSAC,
CIRCUIT,
VALUE,
TOWN;
<强>输出强>:
CUSTOMER CSAC CIRCUIT VALUE TOWN POST_CODE_1 POST_CODE_2
-------- ---------- ---------- -------- -------- ----------- -----------
RCE CSAC125896 ICUK809605 100 MBPS BASILDON SS15 5FS SS15 6AA