2011-06-13 3 views
1

이 내 쿼리입니다 : 내가 할 싶은 무엇는 피벗과 SQL 쿼리의 데이터를 병합하는

Name      Attribute1  Attribute2 
Childs Age:    10 
Attended Camp Before?: Yes 
Childs T-Shirt Size:  large   NULL 
Allergies Description none   NULL 
Phone #     212-555-1212 NULL 
Pickup     Mary Jordan  NULL 

Name= Name of Attribute Column 
Attribute1 = Data is from a free Form 
Attribute2 = Data is from a Drop down Menu 

데이터 회전입니다 :

SELECT ad.Name, av.Value AS Attribute1, ctv.Value AS Attribute2 
FROM AttributeDefinitions AS ad WITH (nolock) 
INNER JOIN AttributeValues AS av WITH (nolock) 
ON  ad.AttributeDefinitionID = av.AttributeDefinitionID 
INNER JOIN AttributeCategories 
ON  ad.AttributeCategoryID = AttributeCategories.AttributeCategoryID 
LEFT OUTER JOIN CodeTableValues AS ctv WITH (nolock) 
ON  av.CodeTableValueID = ctv.CodeTableValueID 
WHERE (AttributeCategories.Name = 'Camp') AND (av.AttributeValueGroupID = 9840) 

내 결과는 다음과 같다 그래서 열 "이름"의 정보가 열 머리글이되고 속성 1의 값을 결합해야합니다. 내 결과는 다음과 같습니다.

*Childs Age Attended Camp Before? Childs T-Shirt Size Allergies Description Phone#  Pickup* 
10   yes     large    none     212-555-1212 Mary Jordan 
+2

어떤 DB 서버 :

이 예에서 살펴 보자? –

+1

SQL Server 2005 이상을 사용하는 경우 [피벗] (http://msdn.microsoft.com/en-us/library/ms177410.aspx) – Magnus

+0

을 사용할 수 있습니다. 선택한 특성까지는 어떤 논리입니까 ? Attribute1은 항상 Attribute2보다 우선 순위가 높습니까? –

답변

0

Oracle DB에서 CASE 문을 사용하여 행을 열로 변환하고 있습니다.

 
select event_date 
     ,sum(case when service_type = 'OCSAC_DEG' then service_count end) ocsac_deg 
     ,sum(case when service_type = 'SMS_ONL' then service_count end) sms_onl   
     ,sum(case when service_type = 'SMS_DEG' then service_count end) sms_deg 
     ,sum(case when service_type = 'DATA_ONL' then service_count end) data_onl   
     ,sum(case when service_type = 'DATA_DEG' then service_count end) data_deg    
from STATS 
where to_char(event_date, 'yyyymm') = to_char(add_months(sysdate,-1), 'yyyymm') 
group by event_date 
order by event_date desc