2011-06-13 78 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

什麼數據庫服務器? – 2011-06-13 20:52:51

+1

如果您使用的是SQL Server 2005或更高版本,則可以使用[Pivot](http://msdn.microsoft.com/zh-cn/library/ms177410.aspx) – Magnus 2011-06-13 20:56:30

+0

選擇哪個屬性的邏輯是什麼? Attribute1總是優先於Attribute2嗎? – 2011-06-14 00:48:25

回答

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