[英]Pivoting and merging data from a sql query
這是我的查詢:
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
我想做的是旋轉數據,以便“名稱”列中的信息成為 header 列,我需要組合屬性 1 和 2 中的值這是我的結果應該看起來像:
*Childs Age Attended Camp Before? Childs T-Shirt Size Allergies Description Phone# Pickup*
10 yes large none 212-555-1212 Mary Jordan
在 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.