한 열에 둘 이상의 행 값을 사용하여 여러 행을 하나로 병합
Nov 19 2020
현재 DB에서 일부 데이터를 검색하는 쿼리를 작성 중입니다. 단 한 행에서 공통 ID로 일부 정보에 액세스해야합니다.
이 쿼리로 :
select
missions_answer.response_id as "response",
crm_player."document" as "document",
missions_question.label as "label",
missions_answertext.body as "bill #",
missions_answerselectmultiple.body as "product",
missions_answerinteger.body as "answer"
from missions_answer
left join missions_question on missions_answer.question_id = missions_question.id
left join missions_answertext on missions_answer.id = missions_answertext.answer_ptr_id
left join missions_answerselectmultiple on missions_answer.id = missions_answerselectmultiple.answer_ptr_id
left join missions_answerinteger on missions_answer.id = missions_answerinteger.answer_ptr_id
left join missions_response on missions_answer.response_id = missions_response.id
left join crm_player on missions_response.player_id = crm_player.id
LEFT JOIN crm_user ON crm_player.user_id = crm_user.id
where missions_answer.response_id = '71788176'
group by missions_answer.response_id, crm_player.document,missions_answertext.body,
missions_question.label,
missions_answerselectmultiple.body ,
missions_answerinteger.body,
crm_user.first_name,
crm_user.last_name
이것이 내가 현재 가지고있는 것입니다.
+ response + document + label + bill # + product + answer
- 71788176 - 79907201 - bill # - 26899 - -
- 71788176 - 79907201 - amount - - - 1
- 71788176 - 79907201 - product - - {"name": "Shoes"} -
- 71788176 - 79907201 - price - - - 25.99
이것이 내가 찾고있는 것입니다.
+ response + document + bill # + product + amount + price
- 71788176 - 79907201 - 26899 - shoes - 1 - 25.99
사용하려고 crosstab
했지만 여전히 찾을 수 없습니다. 미리 힌트 나 도움을 주셔서 감사합니다.
답변
1 S-Man Nov 19 2020 at 09:31
현재 상태에서 다음 FILTER
절을 사용하여 간단히 피벗을 수행 할 수 있습니다 .
데모 : db <> fiddle
SELECT
response,
document,
MAX(bill) FILTER (WHERE label = 'bill') as bill,
MAX(answer) FILTER (WHERE label = 'amount') as amount,
MAX(product) FILTER (WHERE label = 'product') as product,
MAX(answer) FILTER (WHERE label = 'price') as price
FROM t
GROUP BY response, document
원래 테이블이 어떻게 생겼는지 잘 모르겠습니다. 다음과 같은 경우 :
response | document | label | value
-------: | -------: | :------ | :----
71788176 | 79907201 | bill | 26899
71788176 | 79907201 | amount | 1
71788176 | 79907201 | product | shoes
71788176 | 79907201 | price | 25.99
그런 다음 다음과 같이 쿼리를 수정할 수 있습니다.
데모 : db <> fiddle
SELECT
response,
document,
MAX(value) FILTER (WHERE label = 'bill') as bill,
MAX(value) FILTER (WHERE label = 'amount') as amount,
MAX(value) FILTER (WHERE label = 'product') as product,
MAX(value) FILTER (WHERE label = 'price') as price
FROM t
GROUP BY response, document
편집 : 제품 열에 JSON 값을 추가하려면 :
데모 : db <> fiddle
변형 1 : 단순히 유형 json
을 유형으로 캐스팅 할 수 있습니다 text
.
MAX(product::text) FILTER (WHERE label = 'product') as product,
변형 2 : "name"
속성 에서 값을 읽습니다 .
MAX(product ->> 'name') FILTER (WHERE label = 'product') as product,