2011-06-13 17 views
1

からマージするデータは、これは私のクエリです:ピボットとSQLクエリ

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) 

私の結果は次のようになります。

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 

私がやりたいどのようなデータを回転させていますその結果、列「名前」の情報が列ヘッダーになり、属性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サーバー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 
関連する問題