반응형
테이블에서 데이터를 전치 형식으로 검색할 수 있습니까?
아래 형식의 데이터가 있는 테이블이 있습니다.
id | col1 | col2 | col3
1 | d11 | d21 | d31
2 | d12 | d22 | d32
3 | d13 | d23 | d33
4 | d14 | d24 | d34
5 | d15 | d25 | d35
6 | d16 | d26 | d36
아래의 형식으로 데이터를 얻을 수 있습니까?
id | 1 | 2 | 3 | 4 | 5 | 6
col1 | d11 | d12 | d13 | d14 | d15 | d16
col2 | d21 | d22 | d23 | d24 | d25 | d26
col3 | d31 | d32 | d33 | d34 | d35 | d36
기본적인 생각조차 없어요.어떤 것이든 환영입니다.
출력에 이 쿼리를 사용할 수 있습니다.
with cte as (
select id, 'col1' as col , col1 as val from tab
union all
select id, 'col2' as col , col2 as val from tab
union all
select id, 'col3' as col , col3 as val from tab
)
select id, [1], [2], [3], [4], [5], [6] from (
select id, col, val from cte
) as d
pivot (
max(val) for col in ( [1], [2], [3], [4], [5], [6] )
) as p
이것을 확인하고, 이것이 동작하는지 확인해 주세요.
포장을 풀고 다시 포장을 해야 합니다.조건부 집약을 사용할 수 있습니다.
select col,
sum(case when id = 1 then val end) as val_1,
sum(case when id = 2 then val end) as val_2,
sum(case when id = 3 then val end) as val_3,
sum(case when id = 4 then val end) as val_4,
sum(case when id = 5 then val end) as val_5,
sum(case when id = 6 then val end) as val_6
from ((select id, 'col1' as col, col1 as val from t
) union all
(select id, 'col2' as col, col2 as val from t
) union all
(select id, 'col3' as col, col3 as val from t
)
) t
group by col;
언급URL : https://stackoverflow.com/questions/57319808/is-it-possible-to-retrieve-the-data-from-table-in-transpose-format
반응형
'programing' 카테고리의 다른 글
SQL을 사용하여 날짜별로 정렬할 수 있지만 결과 집합의 뒷부분에 늘 날짜를 넣을 수 있습니까? (0) | 2023.02.03 |
---|---|
Vuex - 변환 후 상태 가져오기 (0) | 2023.02.03 |
django.db.db.ss.Operation Error: (2002, "'db'의 MySQL 서버에 접속할 수 없습니다(115)" (0) | 2023.02.03 |
사전 개체의 길이를 확인하는 중입니다. (0) | 2023.02.03 |
MariaDB의 Qcache_hits와 Com_select가 함께 증가합니다. (0) | 2023.02.03 |