2013-01-14 1 views
0

SQL 쿼리의 결과를 여러 열로 표시하는 방법을 만들어야합니다. SQL은 특정 유형의 각 항목 수를 계산하는 것이 매우 기본입니다. DB 결과에서 사용자 정의 테이블 만들기

그래서 SQL 사용자 정의 이름을 가진 열 아래 각 유형의 수를 줄 것이다 나는이 하나 개의 행이있는 테이블에 표시 할

Select count(distinct(id)) from Table where id_type = a 

Select count(distinct(id)) from Table where id_type = b 

Select count(distinct(id)) from Table where id_type = c 

같은 것입니다.

SQL은 다소 희박하므로 추가 외부 정보가 항상 환영받습니다.

+0

하면 피벗 테이블 http://en.wikibooks.org/wiki/MySQL/Pivot_table을 의미합니까? – piotrekkr

답변

2

피벗의 데이터를 열로 입력해야합니다. 당신은 여전히 ​​어떤 이유로 별도의 쿼리를 사용하려면

Select 
    count(distinct case when id_type = 'a' then id end) TotalA, 
    count(distinct case when id_type = 'b' then id end) TotalB, 
    count(distinct case when id_type = 'c' then id end) TotalC 
from Table 

또는, 당신은 사용할 수 있습니다 : 그것은 MySQL의에서 인 경우에이 데이터 변환을 수행하는 CASE 표현으로 집계 함수를 사용해야합니다 UNION ALL 한 다음 컬럼에 데이터를 회전 :

select 
    max(case when col = 'A' then TotalCount end) TotalA, 
    max(case when col = 'B' then TotalCount end) TotalB, 
    max(case when col = 'C' then TotalCount end) TotalC 
from 
(
    Select count(distinct(id)) TotalCount, 'A' Col 
    from Table 
    where id_type = 'a' 
    union all 
    Select count(distinct(id)) TotalCount, 'B' Col 
    from Table 
    where id_type = 'b' 
    union all 
    Select count(distinct(id)) TotalCount, 'C' Col 
    from Table 
    where id_type = 'c' 
) src