透视和合并来自SQL查询的数据

时间:2011-06-13 20:46:14

标签: sql merge pivot

这是我的查询:

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和1的值。 2 这就是我的结果应该是什么样的:

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

1 个答案:

答案 0 :(得分: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