开发者

Pivoting and merging data from a sql query

This is My 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)

My Result Looks Like This:

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   

What I would like to do is Rotate the data so that the information from column “Name” becomes the column header and I need to combine the values from attribute 1 & 2 This is what my Result Should Look Like:

*Childs Age  Attended Camp Before?  Childs T-Shirt Size  Allergies Description Phone#        Pickup*
10           yes           开发者_StackOverflow中文版         large                none                  212-555-1212  Mary Jordan


In Oracle DB I am using CASE statement to convert rows into columns.

Take a look on this example:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜