2017-10-29 1 views
0

SQL 쿼리 질문이 있습니다. 이 같은 내 현재 테이블 모양 : 나는이 같은 출력을 얻을 수 있도록SQL 행 열 변환

+--------+------+-----+-----+------+ 
| hostid | itemname | itemvalue | 
+--------+------+-----+-----+------+ 
| A |  1  |  10 | 
+--------+------+-----+-----+------+ 
| B |  2  |  3  | 
+--------+------+-----+-----+------+ 

어떻게 쿼리를 작성합니다? 는 "피벗"로 알려져 당신이 찾고 있습니다 일반적으로

+--------+-- 
| A | B | 
+--------+-- 
| 1 | 2 | 
+--------+-- 
| 10 | 3 | 
+--------+-- 

답변

0

. 그러나 이것은 2 개의 열을 2 개의 행으로 옮길 수 있도록 작은 "트릭"(cross join 사용)이 필요했습니다. 그런 다음 max()group by이 피벗을 생성하는 데 사용됩니다.

SQL Fiddle

MySQL을 5.6 스키마 설정 :

CREATE TABLE Table1 
    (`hostid` varchar(1), `itemname` int, `itemvalue` int) 
; 

INSERT INTO Table1 
    (`hostid`, `itemname`, `itemvalue`) 
VALUES 
    ('A', 1, 10), 
    ('B', 2, 3) 
; 

검색어 1 :

select a, b 
from (
     select 
      max(case 
      when n = 1 and hostid = 'A' then itemname 
      when n = 2 and hostid = 'A' then Itemvalue 
      end) A 
     , max(case 
      when n = 1 and hostid = 'B' then itemname 
      when n = 2 and hostid = 'B' then Itemvalue 
      end) b 
      , n 
     from table1 
     cross join (select 1 n union all select 2) n 
     group by n 
    ) d 
; 

Results :

| a | b | 
|----|---| 
| 1 | 2 | 
| 10 | 3 | 
+0

질문이 지금 해결 되었습니까? 이 답변에 대해 질문이 있습니까? [help/accepting] (https://stackoverflow.com/help/someone-answers)에 대한 자세한 내용은 "[** 클릭 **] (https://ibb.co/ikqyO6)"대답을 수락하려면 –